How to capture the Return Value of a ScriptBlock invoked with Powershell's Invoke-Command

后端 未结 4 917
猫巷女王i
猫巷女王i 2020-12-13 13:16

My question is very similar to this one, except I\'m trying to capture the return code of a ScriptBlock using Invoke-Command (so I can\'t use the -FilePath option). Here\'s

4条回答
  •  心在旅途
    2020-12-13 13:59

    $remotesession = new-pssession -computername localhost
    invoke-command -ScriptBlock { cmd /c exit 2} -Session $remotesession
    $remotelastexitcode = invoke-command -ScriptBlock { $lastexitcode} -Session $remotesession
    $remotelastexitcode # will return 2 in this example
    
    1. Create a new session using new-pssession
    2. Invoke your scripblock in this session
    3. Fetch the lastexitcode from this session

提交回复
热议问题