How can I correct my foreach loop in powershell for every Active Directory OU user?

Posted on

How can I correct my foreach loop in powershell for every Active Directory OU user? – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about windows, active-directory, powershell, organizational-unit, .

Goal: Create a for or foreach loop to execute some code (in this case, just print x) for every user in an OU.
Im using powershell 2.0, with ActiveDirectory module.

So far: This is what I have (see below). It just prints out the X’s for every user. But its not working how I want it to, instead I think it may be doing it for every line. So I get 6 X’s for ‘name’, ‘—-‘, ‘test1’, ‘test2’, SPACE, SPACE.

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=jack,DC=Corp,DC=jill,DC=com" -Properties name | FT name
foreach ($user in $pool )
{ write-host "x"}

Result, the SPACE will be represented by a period (.) :



I am not sure why it does this.
If you have a better method or way of handling this, I’ll be delighted in hearing it.

Solution :

Your $pool will contain the output of Format-Table name, the last step in the first line. The Format-* cmdlets are used for displaying values on screen. You almost certainly don’t want to feed a formatted table to your foreach loop.

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=jack,DC=Corp,DC=jill,DC=com"
foreach ($user in $pool) {
  Write-Host "x"

# And if you really want to see an `ft $pool`:
$pool | Format-Table name

Leave a Reply

Your email address will not be published. Required fields are marked *