Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ForEach over CSV

I’ve created a script which exports inactive Azure users into a CSV. This CSV contains users which are in various OU’s within onprem AD as we’re hybrid. I’m trying to create another script which loops over the CSV but only targets users within our “Users OU” and moves them to an “Inactive OU”. Here’s what I have so far but I’m a little stumped. I can’t figure out where or how to add in -Filter SearchBase into this.

$inactiveAzure = import-CSV -path “C:\temp\InactiveAzure.csv”

$OUpath = “OU I would like the script to run over” 

$OUTarget = “Inactive OU example”

ForEach($users in $inactiveAzure) {
    Get-ADuser -Identity $users.onPremisesSamAccountName | Move-ADObject -TargetPath $OUTarget
}

Any help would be greatly appreciated.

I’ve tried adding SearchBase into the script but can’t get it to work. I’m not entirely sure how to implement this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Most of the *-AD* cmdlets take a -SearchBase parameter with which you can limit the search to a particular container or subtree:

Get-ADUser -Filter "SamAccountName -eq '$($users.onPremisesSamAccountName)'" -SearchBase $OU | Move-ADObject -TargetPath $OUTarget

When using the -Filter option, Get-ADUser will fail silently if no matching users are found in the given OU, otherwise the user object will be piped to Move-ADObject as expected

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading