Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extraneous data returned from Invoke-Command

I'm working with PowerShell to gather data from a list of remote servers which I then turn into a JSON object. Everything is working fine, but I get some really weird output that I can't seem to exclude.

I've tried piping the Invoke-Command results and excluding properties. I've also tried removing the items manually from the returned hash file, but I can't seem to make them go away.

What am I missing?

EDIT:

For the sake of figuring out what's wrong here is a simplified, but still broken, script:

$returnedServer = @{}
$pass = cat "C:\...\securestring.txt" | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "UserName",$pass
$s = @("xx.xxx.xxx.xxx","xx.xxx.xxx.xxx") 


foreach($server in $s)
{
    $returnedServer.$server += ,(Invoke-Command -ComputerName $server -ScriptBlock 
{
1
}-credential $mycred | select -ExcludeProperty PSComputerName,RunSpaceID,PSShowComputerName) 

$returnedServer| ConvertTo-Json

Which outputs:

{
"xx.xxx.xxx.xxx":  [
                       {
                           "value":  1,
                           "PSComputerName":  "xx.xxx.xxx.xxx",
                           "RunspaceId":  "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                           "PSShowComputerName":  xxxx
                       }
                   ],
"xx.xxx.xxx.xxx":  [
                       {
                           "value":  1,
                           "PSComputerName":  "xx.xxx.xxx.xxx",
                           "RunspaceId":  "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"",
                           "PSShowComputerName":  xxxx
                       }
                   ]
}
like image 960
DiscOH Avatar asked Oct 15 '25 13:10

DiscOH


2 Answers

This post is really old, but I was unable to find an acceptable answer 6 years later, so I wrote my own.

$invokeCommandResults | ForEach-Object {
  $_.PSObject.Properties.Remove('PSComputerName')
  $_.PSObject.Properties.Remove('RunspaceId')
  $_.PSObject.Properties.Remove('PSShowComputerName')
}
like image 136
John Homer Avatar answered Oct 17 '25 04:10

John Homer


You need to use Select-Object to limit the result to just the properties you want to show up in the JSON output:

$returnedServers.$server += ,(Invoke-Command -ComputerName $server -ScriptBlock 
{
...$serverHash = various look ups and calculations...
$serverHash
} | select PropertyA, PropertyB, ...)

For a more thorough answer you need to go into far more detail about your "various look ups and calculations" as well as the actual conversion to JSON.

like image 25
Ansgar Wiechers Avatar answered Oct 17 '25 03:10

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!