简体   繁体   中英

Move all AD users from one OU to another

I need some assistance as I am stuck trying to write a simple PS script that will roll users to the next OU.

For an example, I would like to move all accounts from test1 to test2 :

$ou1 = 'OU=test1,OU=users,DC=contoso,DC=local'
$ou2 = 'OU=test 2,OU=users,DC=contoso,DC=local'

$adUserGroup = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou1) -Properties $properties | Select-object $properties | Sort-Object samAccountName

foreach($user in $adUserGroup)
    {
    "Moving Active Directory user $($user.Name)"
    move-adobject -Identity "$user" -targetpath $ou2
    }

You don't define $properties anywhere, so Select-Object isn't actually doing anything. It can be removed as it's not really needed for this task as the default properties are fine.

Sort-Object is also not required unless you really care that the users are moved in alphabetical order of their username..

I would also change Filter as it doesn't need a scriptblock { } -- it can just be quoted ' '

$ou1 = 'OU=test1,OU=users,DC=contoso,DC=local'
$ou2 = 'OU=test 2,OU=users,DC=contoso,DC=local'

$AdUsers = Get-ADUser -Filter 'Enabled -eq "True"' -SearchBase $ou1

foreach($user in $AdUsers) {
    Write-Output "Moving Active Directory user: $($user.Name)"
    Move-ADObject -Identity $user -TargetPath $ou2
}

You can actually use the pipeline to make the process a single command, using -Verbose to provide output about which user it's moving:

$ou1 = 'OU=test1,OU=users,DC=contoso,DC=local'
$ou2 = 'OU=test 2,OU=users,DC=contoso,DC=local'

Get-ADUser -Filter 'Enabled -eq "True"' -SearchBase $ou1 | Move-ADObject -TargetPath $ou2 -Verbose

您可以通过不使用变量将其设为一行

Get-ADUser -Filter 'Enabled -eq "True"' -SearchBase 'OU=test1,DC=contoso,DC=com' | Move-ADObject -TargetPath 'OU=Test2,DC=contoso,DC=com' -Verbose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM