我有一个功能齐全的脚本来导入和创建AD用户,但我想跳过尝试创建已经在AD中的用户。
Import-Module ActiveDirectory
$CsvPath = "C:\Shares\Users.csv"
$CsvTest = Test-Path $CsvPath
Import-Csv $CsvPath | ForEach-Object {
Get-AdUser $_.sAMAccountName
}
Import-Csv $CsvPath | ForEach-Object {
New-ADUser -Name $_.Name -UserPrincipalName $_.userPrincipalName -SamAccountName $_.sAMAccountName -DisplayName $_.DisplayName -GivenName $_.GivenName -Surname $_.Surname -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -force) -Enabled $true -ChangePasswordAtLogon $true
{
Catch [Microsoft.ActiveDirectory.Management.Commands.NewADUser]
}
$_."sAMAccountName"; "already exists"
}
答案 0 :(得分:0)
这样的事情不依赖于例外会更好:
Import-Module ActiveDirectory
$csvPath = "C:\Shares\Users.csv"
if (Test-Path $csvPath)
{
$newUsers = Import-Csv $csvPath
$existingUsers = Get-ADGroupMember "Domain Users"
foreach ($newUser in $newUsers)
{
if (($existingUsers | Where-Object { $_.sAMAccountName -eq $newUser.sAMAccountName }) -eq $null)
{
$user = New-ADUser -Name $newUser.Name -UserPrincipalName $newUser.userPrincipalName -SamAccountName $newUser.sAMAccountName -DisplayName $newUser.DisplayName -GivenName $newUser.GivenName -Surname $newUser.Surname -AccountPassword (ConvertTo-SecureString $newUser.Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true
}
}
}
我个人更喜欢将Quest AD模块用于Powershell,因为当对象不存在时返回$ null可以避免异常。