Home > Mobile >  Move list of users from one OU to a different OU and disable them at the same time - Powershell
Move list of users from one OU to a different OU and disable them at the same time - Powershell

Time:02-02

I currently have a script that is able to disable a list of usernames using a text file which has a list of username specified:

$users = Get-Content C:\disableusers.txt

foreach ($user in $users) {
    Disable-ADAccount -Identity $user
    Write-Host "user $($user) has been disabled"
}

I was wondering if it is possible to incorporate moving using from one OU to another during the execution of this script?

e.g. moving from "Users" OU to "Disabled Users" OU.

I have created another script which does move a list of usernames to "Disabled Users" OU:

$users=Get-Content C:\disableusers.txt

$OU = "distinguishedName of my Disable Users OU"

foreach ($user in $users) {
    Get-ADUser $user | Move-ADObject -TargetPath $OU 
}

Any help on this is much appreciated thanks.

CodePudding user response:

Both of your snippets look good to me, if you are interested in combining them into one you could use -PassThru from Disable-ADAccount to pass the disabled object through the pipeline to Move-ADObject:

$OU = "distinguishedName of my Disable Users OU"

Get-Content C:\disableusers.txt | ForEach-Object {
    try {
        Disable-ADAccount $_ -PassThru |
            Move-ADObject -TargetPath $ou

        Write-Host "user $($user) has been disabled and moved"
    }
    catch {
        Write-Error $_
    }
}
  • Related