📌  相关文章
📜  powershell 从名字和姓氏获取 samaccountname - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:45:37.727000             🧑  作者: Mango

PowerShell 从名字和姓氏获取 SAMAccountName

PowerShell 是一种命令行工具,可帮助开发人员自动化各种任务。在本教程中,我们将讨论如何使用 PowerShell 从名字和姓氏获取 SAMAccountName。

获取用户输入

首先,我们需要要求用户输入名字和姓氏。我们可以通过 Read-Host cmdlet 从用户获取输入。以下是一个示例:

# Get user input for first name and last name
$firstName = Read-Host "Enter first name:"
$lastName = Read-Host "Enter last name:"

以上代码将从用户获取名字和姓氏,并将它们存储在 $firstName$lastName 变量中。

连接到 Active Directory

接下来,我们需要连接到 Active Directory 来查找用户的 SAMAccountName。我们可以使用 Get-ADUser cmdlet 查询 Active Directory。以下是一个示例:

# Import Active Directory module
Import-Module ActiveDirectory

# Connect to Active Directory
$domainName = "mydomain.com"
$username = "administrator"
$password = "mypassword"
$domain = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $domainName, $username, $password)

以上代码将加载 Active Directory 模块并连接到 Active Directory。请注意,您需要将 mydomain.comadministratormypassword 替换为您的域名、用户名和密码。

查找用户的 SAMAccountName

现在,我们可以使用 Get-ADUser 来查找用户的 SAMAccountName。以下是一个示例:

# Get the user's SAMAccountName
$user = Get-ADUser -SearchBase "DC=mydomain,DC=com" -Filter {(givenName -eq $firstName) -and (surName -eq $lastName)} -Properties *
$samAccountName = $user.SAMAccountName

以上代码将查找名字和姓氏匹配的用户,并将其 SAMAccountName 存储在 $samAccountName 变量中。

完整代码

以下是完整的 PowerShell 代码:

# Get user input for first name and last name
$firstName = Read-Host "Enter first name:"
$lastName = Read-Host "Enter last name:"

# Import Active Directory module
Import-Module ActiveDirectory

# Connect to Active Directory
$domainName = "mydomain.com"
$username = "administrator"
$password = "mypassword"
$domain = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $domainName, $username, $password)

# Get the user's SAMAccountName
$user = Get-ADUser -SearchBase "DC=mydomain,DC=com" -Filter {(givenName -eq $firstName) -and (surName -eq $lastName)} -Properties *
$samAccountName = $user.SAMAccountName

# Output the SAMAccountName
Write-Host "SAMAccountName for $firstName $lastName is $samAccountName"
总结

在本教程中,我们讨论了如何使用 PowerShell 从名字和姓氏获取 SAMAccountName。通过连接到 Active Directory 并使用 Get-ADUser cmdlet,我们可以轻松地查找用户的 SAMAccountName。现在我们回答了此问题,您可以尝试使用 PowerShell 来执行其他自动化任务。