如何在 PowerShell 工作流中執行 Invoke-Command?


要在 PowerShell 工作流中執行 Invoke-Command,我們需要使用 InlineScript 塊,因為 Invoke-Command 不直接在工作流中受支援。以下示例未使用 InlineScript 塊,我們收到一個錯誤。

示例

Workflow TestInvokeCommand{
   Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
      Get-Service WINRM
   }
}

輸出 −

At line:2 char:5
+    Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot call the 'Invoke-Command' command. Other commands from this module have been packaged as workflow activities, but this
command was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has
behavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Invoke-Command })
where it will be invoked in isolation.
   + CategoryInfo : ParserError: (:) [], ParseException
   + FullyQualifiedErrorId : CommandActivityExcluded

上述錯誤表明 Invoke-Command 無法直接與 PowerShell 一起使用,我們需要在 InlineScript 塊中使用它,如下所示。

Workflow TestInvokeCommand{
   InlineScript{
      Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
         Get-Service WINRM
      }
   }
}

TestInvokeCommand

要在 InlineScript 塊中的指令碼塊中使用外部變數,我們需要使用 $Using:VariableName。例如,

示例

Workflow TestInvokeCommand{
$server = "Labmachine2k16"
   InlineScript{
       Invoke-Command -ComputerName $using:Server -ScriptBlock{
           Get-Service WINRM
       }
   }
}

TestInvokeCommand

要儲存輸出變數,

輸出

Workflow TestInvokeCommand{
   $server = "Labmachine2k16"
   $Status =  InlineScript{
      Invoke-Command -ComputerName $using:Server -ScriptBlock{
         return( Get-Service WINRM).Status
      }
   }
   Write-Output "WinRM Status: $status"
}
 
TestInvokeCommand

更新時間:19-2 月-2021

1K+ 瀏覽量

開啟您的職業

完成課程後獲取認證

開始
廣告
© . All rights reserved.