前言:
工作中难免遇到需要大量创建域用户或域计算机的需求,我这边整理了一份常用的PowerShell运维脚本,并实践验证过,只需要将脚本中的OU和部分命名规则替换成你环境中的信息就可以直接运行。
指定OU内批量创建计算机
脚本内容
$ouPath = "OU=VDI,DC=test,DC=local"
1..100 | ForEach-Object {
$computerNumber = $_.ToString("000")
$computerName = "nuonuo-$computerNumber"
New-ADComputer -Name $computerName -Path $ouPath
}
脚本输出
指定OU内批量创建用户
首先需要创建一个csv表项,假设文件名为users.csv,文件格式为:"FirstName,LastName,Username,Password"
脚本内容
$ouPath = "OU=测试用户,DC=test,DC=local"
$csvPath = "C:\Users\Administrator\Desktop\users.csv"
$users = Import-Csv -Path $csvPath
foreach ($user in $users) {
$userName = $user.UserName
$password = ConvertTo-SecureString -String $user.Password -AsPlainText -Force
$userParams = @{
SamAccountName = $userName
UserPrincipalName = "$userName@test.local"
Name = $userName
GivenName = $user.FirstName
Surname = $user.LastName
DisplayName = $user.DisplayName
Path = $ouPath
AccountPassword = $password
Enabled = $true
}
New-ADUser @userParams
}
脚本输出
批量移动指定OU下计算机账户到其他OU
脚本内容
$sourceOU = "OU=VDI-1,DC=test,DC=local"
$targetOU = "OU=VDI-2,DC=test,DC=local"
$filter = {
Name -like "nuonuo*"
}
$computers = Get-ADComputer -Filter $filter -SearchBase $sourceOU
foreach ($computer in $computers) {
Move-ADObject -Identity $computer -TargetPath $targetOU
}
脚本输出
将链接的GPO复制到其他OU
该需求适用于OU下链接了较多的GPO,不便于逐步每条单独手动链接的情况下使用。
脚本内容
Copy-GPOLinks -SourceOU 'OU=VDI-1,DC=test,DC=local' -TargetOU 'OU=VDI-2,DC=test,DC=local'
复制所有链接的GPO,并创建所有缺失的OU
Copy-GPOLinks -SourceOU 'OU=VDI-1,DC=test,DC=local' -TargetOU 'OU=VDI-2,DC=test,DC=local' -CopyMode Replace -Recurse -CreateMissingChilds
脚本输出