如何检查AD用户名是否已被使用

预先感谢您的帮助。 我在下面的链接find了一些相关的东西,但无法通过这里find我正在寻找的解决scheme。 使用Powershell脚本检查域帐户的存在

我想要做的是从已经生成的CSV文件从我正在运行的另一个脚本的列表中获取用户名。

一旦我有这些用户名(sAMAccountname)我想检查,如果该用户名已被使用。 如果是我希望显示,也许通过Echo,然后继续检查其他名称。 如果不是那么它应该继续检查其他的名字。

这是我到现在为止。 (请记住,我是一个完整的PowerShell新手,我只是做这个绝对需要)

Import-Module ActiveDirectory -ErrorAction Continue $UserCSV = import-csv "\\fs1\DisasterRecovery\Source Controlled Items\WindowsPowerShell\Test scripts\Import Production Users\Users.csv" $UserList = $UserCSV.sAMAccountname foreach($User in $UserList) { if (Get-ADUser -Filter {sAMAccountname -eq $User} ) { # Exists #echo Already Exists } else { SilentlyContinue } } 

如果您使用Powershell 3或更高版本,则不需要Import-Module ActiveDirectory 。 只要使用该模块的cmdlet,PS就会自动为您加载模块。 使用$PSVersionTable知道肯定,但我认为你正在使用PS 3或更好,因为你似乎在你的代码中使用自动的foreach,自动的foreach直到PS 3才能使用。

而且,如果模块无法加载, -ErrorAction Continue是没有意义的,因为这对于脚本的其余部分是至关重要的,所以-ErrorAction Continue也没有意义。 我打全部的第一行。

第二行你inputCSV是好的。 $UserListvariables似乎是多余的。 从那里我可能会做这样的事情:

 $UserCSV = Import-Csv C:\Users\Administrator\test.csv Foreach ($User in $UserCSV) { Try { # Use "EA Stop" to ensure the exception is caught. $U = Get-ADUser $User.sAMAccountName -ErrorAction Stop Write-Host "$($User.SamAccountName) is already in use." } Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { # The user was not found! Write-Warning "$($User.SamAccountName) was not found in this domain!" } Catch { # Some other terrible error occured! Write-Error "OHSHI" } } 

我没有testing过这个,但是结构会更像:

 Import-Module ActiveDirectory -ErrorAction Continue $UserCSV = import-csv "\\fs1\DisasterRecovery\Source Controlled Items\WindowsPowerShell\Test scripts\Import Production Users\Users.csv" foreach($row in $UserCSV) { $userAccount = Get-ADUser -Filter {sAMAccountname -eq $row.sAMAccountname} if ($userAccount) { Write-Host "User $($row.sAMAccountname) exists" } } 

我认为最好不要为用户testingsAMAccountname的存在,组也可以有相同的sAMAccountname。 这可以通过使用Get-ADObject来完成。这样就不会抛出exception,但是你可以自己抛出一个exception。

 $sAMAccountname = "TestToTest" if(@(Get-ADObject -Filter { sAMAccountname -eq $sAMAccountname }).Count -ge 1){ Write-Host "$sAMAccountname exsists" }else{ Write-Host "$sAMAccountname doesn't exsist" }