How to work with Invoke-Command Scriptblock output?

PowerShellMicrosoft TechnologiesSoftware & Coding

When we simply write the Invoke-Command, it shows the output on the console.

Example

Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service}

Output

It shows the output along with the computer name.

Now let's say you want to sort the output or you want to work with the output you need to store it. It is similar like we store the output in the variable but we can’t store the output inside the scriptblock and display it outside.

$ser = @()
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service}
Write-Output "Services output"
$ser

You won’t get any output of the above command because Invoke-Command is known to work on the remote computer. Instead, we can use the RETURN command to return the output to the main console.

$ser = @()
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {$ser = Get-Service
   return $ser
}
Write-Output "Services output"
$ser

You will get the output shown in the first image. You can also store the entire output in the variable if you further want to work with the output.

Example

$sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock { Get-Service}
Write-Output "Services output"
$sb

You can also filter the above output.

$sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service}
Write-Output "Services output"
$sb | Select Name, Status
raja
Published on 04-Jan-2021 10:00:53
Advertisements