这应该足够动态。您可以将 Map 对象替换为 CSV。
$Map = [PSCustomObject]@{
AABBCC = "OU=ABC,DC=Contoso,DC=com";
CCBBAA = "OU=CBA,DC=Contoso,DC=com"
}
$Prefixlist = ($Map.PSObject.Members | Where-Object { $_.MemberType -eq "NoteProperty" }).Name
$Report = @()
$MissingPrefix = @()
Get-ADComputer -filter * -searchbase "CN=Computers,DC=Contoso,DC=com" -Properties Name | ForEach-Object {
$obj = $_
$Prefix = ($obj.Name).Substring(0, 6)
if ($Prefixlist -contains $Prefixlist) {
try {
$obj | Move-AdObject -Targetpath $Map.$Prefix -erroraction stop
$Report += [PSCustomObject]@{
Name = $Obj.Name
Move = $true
}
}
catch {
$_.Exception.ErrorRecord
$Report += [PSCustomObject]@{
Name = $Obj.Name
Move = $false
}
}
}
else {
$MissingPrefix += $Prefixlist
$Report += [PSCustomObject]@{
Name = $Obj.Name
Move = $false
}
}
}
"Result"
$Report | Format-Table -AutoSize
"Not found prefix list"
$MissingPrefix
选项 2 根据前缀创建路径
$Report = @()
Get-ADComputer -filter * -searchbase "CN=Computers,DC=Contoso,DC=com" -Properties Name | ForEach-Object {
$obj = $_
$Prefix = ($obj.Name).Substring(0, 6)
try {
$obj | Move-AdObject -Targetpath "OU=Computers,OU=$Prefix,DC=Contoso,DC=com" -erroraction stop
$Report += [PSCustomObject]@{
Name = $Obj.Name
Move = $true
}
}
catch {
$_.Exception.ErrorRecord
$Report += [PSCustomObject]@{
Name = $Obj.Name
Move = $false
}
}
}
"Result"
$Report | Format-Table -AutoSize