Powershell sorting data in Invoke-Command results

43 Views Asked by At

I'm running an exe from invoke-command on multiple servers and it works. I get a string array with all the output I expect.

$result = invoke-command $servers { & "\path\toexe" arg1 }

This gives me the correct results

str3
str4
str2

...and the PSCOMPUTER name is in there too, but I can't show them together so I can't match the result to the PSComputername all at once.

$Result|GM just shows me PScomputername and RunspaceID as properties. It's like the $result array has no label for the string.

$result | Select * doesn't show me the string

$Result.gettype() shows it is [object] System.Array

I can do $result[0] will show me str3
And then $result[0].PSComputername will show Server3

How do I get that whole array on the screen or dumped to csv together? I'd like to see

PSCOMPUTERNAME   ??
Server3        str3
Server2        str2
2

There are 2 best solutions below

1
Mathias R. Jessen On BEST ANSWER

You can use Select-Object to create new objects consisting of the attached PSComputerName property along with a new named property containing the intrinsic value of the original string:

$result |Select-Object PSComputerName,@{Name='Value';Expression={"$_"}}

To learn more about using Select-Object with property expressions, see the about_Calculated_Properties help topic

0
js2010 On

I usually package the result in an object. This could be a script too. Unless the object type has a local view file, there's a runspaceid displayed too.

invoke-command $servers { [pscustomobject]@{result = \to` path\toexe arg1} }

result PSComputerName RunspaceId
-----  -------------- ----------
str3   Server3        5f8b7b5e-840d-4790-896a-d68aa23f1c01
str2   Server2        3b37b3d7-f1d0-433a-a387-65c4c3a59a5d

<# script.ps1 #>
[pscustomobject]@{result = \path\toexe arg1}
invoke-command $servers script.ps1

# same result