如何處理 Invoke-Command Scriptblock 輸出?


當我們只寫 Invoke-Command 時,它會在控制檯上顯示輸出。

示例

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

輸出

它顯示了輸出和計算機名稱。

現在假設你想對輸出進行排序,或者你想處理需要儲存的輸出。它類似於我們把輸出儲存在變數中,但我們不能儲存在 scriptblock 中的輸出並將它顯示在外。

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

你不會得到上述命令的任何輸出,因為 Invoke-Command 已知在遠端計算機上工作。相反,我們可以使用 RETURN 命令將輸出返回到主控制檯。

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

你將得到第一張圖片中顯示的輸出。如果你還想進一步處理輸出,你還可以將整個輸出儲存在變數中。

示例

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

你還可以過濾上述輸出。

$sb = Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock {Get-Service}
Write-Output "Services output"
$sb | Select Name, Status

更新於: 04-Jan-2021

8K+ 瀏覽

開啟您的職業生涯

完成課程獲得認證

開始使用
廣告