≡ Menu

Why am I getting powershell output in @{parametername=parametervalue}.parametername

One of my friend is trying to get computers list from active directory using below code. All he want is names of the computers in a array.

$TestPcNames = Get-QAComptuer -Id TEST* | select Name            
$TestPCNames | % { write-host "$_.Name" }

There is nothing really wrong with the above code. All it contains is computer names but in object format. For that reason when he is trying to print the computer name, he is getting something like @{Name=TESTPC1}.Name

There he is stuck and now don’t know how to get list of computer accounts(in string format) in a array. This is very basic problem that every system administrator will face when trying to get their hands wet with powershell. I have also gone through this a couple of years back when I am studying ABCs of powershell.

The solution for this is very easy. First get the things printed correctly. You can use either of below one liners for that.

$TestPCNames | % { write-host "$($_.Name)" }         

$TestPCNames | % { $_.Name }

Once you seen them printed as string array(you will noted there won’t be any column header with work “Name”), all you need to do is assign the output to a variable.

$CompArray = $TestPCNames | % { write-host "$($_.Name)" }            
$CompArray = $TestPCNames | % { $_.Name }

Now $CompArray contains the list of computers. Hope this little tip helps…