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

后端 未结 4 900
猫巷女王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:55

    $script = {
        # Call exe and combine all output streams so nothing is missed
        $output = ping badhostname *>&1
    
        # Save lastexitcode right after call to exe completes
        $exitCode = $LASTEXITCODE
    
        # Return the output and the exitcode using a hashtable
        New-Object -TypeName PSCustomObject -Property @{Host=$env:computername; Output=$output; ExitCode=$exitCode}
    }
    
    # Capture the results from the remote computers
    $results = Invoke-Command -ComputerName host1, host2 -ScriptBlock $script
    
    $results | select Host, Output, ExitCode | Format-List
    

    Host : HOST1
    Output : Ping request could not find host badhostname. Please check the name and try again
    ExitCode : 1

    Host : HOST2
    Output : Ping request could not find host badhostname. Please check the name and try again.
    ExitCode : 1

提交回复
热议问题