根据公司的需要,写了一个同时新建AD账号、邮箱、添加通讯组的powershell脚本,首先需要编辑csv文件,格式如下:
代码如下,加入了重名判断、添加到组延迟6秒运行、失败后重现尝试4次功能:
Import-Module ActiveDirectory $erroractionpreference = "SilentlyContinue" #判断是否有重名账号存在 $f = $False Import-Csv -Path D:\newuser\Info.csv | foreach { $a = Get-ADUser -Identity $_.account if($a -ne $null){ echo ($_.account+‘账户在AD中已经存在了。‘) $f = $true } else { } $a = $null } if($f -eq $true){ echo 请在csv文件中修改以上用户名后,重新运行脚本。 cmd /c pause exit } else{echo 没有重名的用户名,正在加载Exchange模块和新建用户账号,请稍等。。。} #新建账号和邮箱 $erroractionpreference = "Continue" Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 $password = ConvertTo-SecureString -AsPlainText 6yhn^YHN -Force Import-Csv -Path D:\newuser\Info.csv | foreach { New-Mailbox -Name $_.name -Alias $_.account -OrganizationalUnit ‘teset.com/teset/newuser‘ -UserPrincipalName ($_.account+‘@teset.com‘) -SamAccountName $_.account -DisplayName $_.name -Password $password -Database ‘User04‘ -ResetPasswordOnNextLogon $true } $erroractionpreference = "SilentlyContinue" #添加到相应的组 choice /t 6 /d y /n |Out-Null Import-Csv -Path D:\newuser\Info.csv | foreach { $b = 1 $b = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf SHoffice if($b -eq $null){ echo ($_.account+‘加入SHoffice组成功‘) } else{ $b = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf SHoffice if($b -eq $null){ echo ($_.account+‘加入SHoffice组成功‘) } else{ $b = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf SHoffice if($b -eq $null){ echo ($_.account+‘加入SHoffice组成功‘) } else{ $b = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf SHoffice if($b -eq $null){ echo ($_.account+‘加入SHoffice组成功‘) } else{ echo ($_.account+‘加入SHoffice组失败!!‘) } } } } $c = 2 $c = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf $_.group1 if($c -eq $null){ echo ($_.account+‘加入‘+$_.group1+‘组成功‘) } else{ $c = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf $_.group1 if($c -eq $null){ echo ($_.account+‘加入‘+$_.group1+‘组成功‘) } else{ $c = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf $_.group1 if($c -eq $null){ echo ($_.account+‘加入‘+$_.group1+‘组成功‘) } else{ $c = Add-ADPrincipalGroupMembership -Identity $_.account -MemberOf $_.group1 if($c -eq $null){ echo ($_.account+‘加入‘+$_.group1+‘组成功‘) } else{ echo ($_.account+‘加入‘+$_.group1+‘组失败!!‘) } } } } } cmd /c "pause"
执行成功后:
有问题,给我留言,一起讨论。
本文出自 “上帝的翅膀” 博客,请务必保留此出处http://lvht6.blog.51cto.com/763105/1693466
同时新建AD账号、邮箱、添加通讯组的powershell脚本
原文地址:http://lvht6.blog.51cto.com/763105/1693466