批量创建用户域账号
事先判断账号是否存在,然后执行添加用户的操作:
Import-Csv -Path "C:\test.csv" -Encoding Default | foreach { # first,last,displayname,description,sam,upn,password $pwd = ConvertTo-SecureString $_.password -AsPlainText -Force $sam = $_.sam $exist = Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(samaccountname=$sam))" -SearchBase 'DC=abc,DC=cn' if($exist) { $_.first + ' is exist!' } else { New-ADUser -AccountPassword $pwd ` -Enabled $true ` -Name $_.displayname ` -Path 'OU=xyz,DC=abc,DC=cn' ` -GivenName $_.first ` -Surname $_.last ` -DisplayName $_.displayname ` -SamAccountName $_.sam ` -UserPrincipalName $_.upn ` -Description $_.description $_.first + ' is created!' } }
不判断用户是否存在,改由捕捉系统错误来进行判断:
$users = Import-Csv -Path "C:\test.csv" -Encoding Default ForEach($user in $users) { # first,last,displayname,description,sam,upn,password $pwd = ConvertTo-SecureString $user.password -AsPlainText -Force try { New-ADUser -AccountPassword $pwd ` -Enabled $true ` -Name $user.displayname ` -Path 'OU=xyz,DC=abc,DC=cn' ` -GivenName $user.first ` -Surname $user.last ` -DisplayName $user.displayname ` -SamAccountName $user.sam ` -UserPrincipalName $user.upn ` -Description $user.description } # 通过$error[0] | fl * -f可以查看出错信息的exception,供catch使用 catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException] { $user.displayname + " is exists!" } finally { } }
另一种需要注意的写法:
Import-Csv -Path "C:\Users\chend\Desktop\test.csv" -Encoding Default | ForEach { # first,last,displayname,description,sam,upn,password $displayname = $_.displayname $pwd = ConvertTo-SecureString $_.password -AsPlainText -Force try{ New-ADUser -AccountPassword $pwd ` -Enabled $true ` -Name $displayname ` -Path 'OU=xyz,DC=abc,DC=cn' ` -GivenName $_.first ` -Surname $_.last ` -DisplayName $displayname ` -SamAccountName $_.sam ` -UserPrincipalName $_.upn ` -Description $_.description } # 通过$error[0] | fl * -f可以查看出错信息的exception,供catch使用 catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException] { $displayname + " is exists!" # 这样是无法显示displayname的,必须将$_.displayname单独赋给一个变量 } }