Search code examples
arrayspowershellpowershell-4.0get-childitem

With Powershell, how do I populate a variable with the name of objects I get from Get-ChildItem?


With Powershell, how do I populate a variable with the name of an object I get from Get-ChildItem?

Say, for example, I'm trying to get the names of OUs (so I can do input validation) under a given search base.

I can easily use a temp variable and do something like:

$ValidSites = Get-ChildItem -Path AD:\"OU=SomeOU,DC=contoso,DC=com" | Where-Object { $_.ObjectClass -eq "organizationalUnit" }
$ValidSiteNames = @("","","","","","","","","")

For ($i=0; $i -lt $ValidSites.Length; $i++) {

$ValidSiteNames[$i] = $ValidSites[$i].name

}

But, that's hacky and I end up with an extra variable I don't want or need (and, also extra effort and code).

I've tried piping to a Select statement (with | Select $_.name), but that's not giving me the expected results (just returns the same objects as if it wasn't there), so I'm not sure what else to try.

How do I just the names of these objects returned by Get-ChildItem into an array without the extra effort and code involved in a temp variable and for loop?


Solution

  • The below line is working to create an array of names into $ValidSites.

    $ValidSites = Get-ChildItem -Path AD:\"OU=SomeOU,DC=contoso,DC=com" | Where-Object { $_.ObjectClass -eq "organizationalUnit" } | select -expand name