0

Trying to run a command in a foreach loop that contains different search locations, e.g.:

$ous ='ou=Staff,dc=example,dc=local', 'ou=Managers,dc=example,dc=local'

$colItems = $ous | ForEach { Get-ADUser -Filter * -SearchBase "ou=Example,dc=example,dc=local" -Properties whenCreated | select -Property Enabled,Name,SamAccountName,whenCreated }

I want to replace the OU in the search query each time

"ou=Example,dc=example,dc=local"

2 Answers 2

1

If you use a pipeline with a ForEach-Object loop, you must use the current object variable ($_) to refer to the current object from the pipeline. Change this:

$ous | ForEach { Get-ADUser -Filter * -SearchBase "ou=Example,dc=example,dc=local" -Properties ... }

into this:

$ous | ForEach-Object { Get-ADUser -Filter * -SearchBase $_ -Properties ... }

See about_Automatic_Variables for more information.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this was my answer.

$colItems = ForEach ($ou in $ous) { Get-ADUser -Filter * -SearchBase $ou -Properties whenCreated | select -Property Enabled,Name,SamAccountName,whenCreated }

1 Comment

please use foreach($ou in $ous) (without the uppercase letters) - lessens confusion between the foreach loop construct and the ForEach-Object cmdlet alias

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.