AD域批量运维管理脚本
注意:以下操作都需要以管理员权限运行powersehll命令才行执行成功。
1 批量创建计算机账户
$ouPath = "OU=computer,OU=Citrix,DC=citrixlab,DC=local" 1..100 | ForEach-Object { $computerNumber = $_.ToString("000") #此为占位符 $computerName = "CVAD-$computerNumber" New-ADComputer -Name $computerName -Path $ouPath }
2 批量创建AD域账号
表格示例,按此方式批量添加,可新建Excel表格,名称建议为aduser.xlsx 点击下载模块
name | SamAccountName | UserPrincipalName | AccountPassword | Enabled | Description | path |
邓鹏 | dengpeng | dengpeng@powershell.com.cn | P@ssw0rd | $True | 技术部 | OU=技术部,DC=powershell,DC=com,DC=cn |
# 导入Excel文件的模块,需要先导入此模块才行 Import-Module ImportExcel # 读取 Excel 文件,这里是把文件放在itadmin的桌面上。 $excelData = Import-Excel -Path C:\Users\itadmin\Desktop\aduser.xlsx # 遍历每一行数据,创建AD用户 foreach ($user in $excelData) { # 获取用户信息 $name = $user.name $samAccountName = $user.SamAccountName $userPrincipalName = $user.UserPrincipalName $accountPassword = ConvertTo-SecureString $user.AccountPassword -AsPlainText -Force $enabled = $user.Enabled -eq '$True' # 将 $True 转为布尔值 $description = $user.Description $ouPath = $user.path # 创建用户 New-ADUser -Name $name ` -SamAccountName $samAccountName ` -UserPrincipalName $userPrincipalName ` -AccountPassword $accountPassword ` -Enabled $enabled ` -Description $description ` -Path $ouPath ` -PassThru Write-Host "创建用户 $name 完成" }
3 批量移动指定OU下计算机账户到另外OU
$sourceOU = "OU=Computers,OU=DepartmentA,DC=example,DC=com" $targetOU = "OU=VDI Computers,OU=DepartmentB,DC=example,DC=com" $filter = { Name -like "VDI*" } $computers = Get-ADComputer -Filter $filter -SearchBase $sourceOU foreach ($computer in $computers) { Move-ADObject -Identity $computer -TargetPath $targetOU }
4 按条件删除指定OU下的计算机账户
$ouPath = "OU=Computers,OU=DepartmentA,DC=example,DC=com" $filter = { Enabled -eq $true -and #选择禁用的 OperatingSystem -like "*Server*" -and #选择是server的系统 (Search-ADAccount -ComputersOnly -AccountDisabled).Count -eq 0 -and #排除已禁用的计算机 Description -eq "To be deleted" } $computers = Get-ADComputer -Filter $filter -SearchBase $ouPath foreach ($computer in $computers) { Remove-ADComputer -Identity $computer -Confirm:$false }
5 按条件删除指定OU下的域账号
$ouPath = "OU=Users,OU=DepartmentA,DC=example,DC=com" $filter = { Enabled -eq $true -and (Search-ADAccount -UsersOnly -AccountDisabled).Count -eq 0 -and Description -eq "To be deleted" } $users = Get-ADUser -Filter $filter -SearchBase $ouPath foreach ($user in $users) { Remove-ADUser -Identity $user -Confirm:$false -Recursive -Force }