Controlling PSComputerName in Remoting Data with PowerShell

by Sep 28, 2012

Whenever you use Invoke-Command to remotely execute code, you will notice that PowerShell automatically adds the column PSComputerName to your results. That's great because when you run Invoke-Command against more than one computer, you want to still know which computer returned particular information.

Invoke-Command { Get-Service } -ComputerName PC1, PC2, PC3

If this does not work for you, make sure you enabled and configured PowerShell Remoting correctly first.

The problem with PSComputerName is: it disappears whenever you use Select-Object to tailor the resulting columns:

Invoke-Command { Get-Service } -ComputerName PC1, PC2, PC3 | Select-Object PSComputerName, Name, Status

To work around this problem, define a hash table to add the sender’s name. As a side effect, you now can also give the column a better name:

$pcname = @{
    Name = 'Machine'
    Expression = { $_.PSComputerName }
  }
Invoke-Command { Get-Service } -ComputerName PC1, PC2, PC3 | Select-Object $pcname, Name, Status

Twitter This Tip! ReTweet this Tip!