35

私の質問はこれと非常に似ていますが、Invoke-Command を使用して ScriptBlock のリターン コードを取得しようとしています (したがって、-FilePath オプションは使用できません)。これが私のコードです:

Invoke-Command -computername $server {\\fileserver\script.cmd $args} -ArgumentList $args
exit $LASTEXITCODE

問題は、Invoke-Command が script.cmd のリターン コードをキャプチャしないことです。そのため、失敗したかどうかを知る方法がありません。script.cmd が失敗したかどうかを知る必要があります。

New-PSSession も使用してみました (これにより、リモート サーバーで script.cmd の戻りコードを確認できます) が、それを呼び出し元の Powershell スクリプトに戻して、実際に失敗について何かを行う方法が見つかりません。

4

5 に答える 5

44
$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. new-pssession を使用して新しいセッションを作成する
  2. このセッションでスクリプトブロックを呼び出します
  3. このセッションから最後の終了コードを取得します
于 2011-12-18T08:51:10.190 に答える
8
$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

ホスト: HOST1
出力: ping 要求は、ホスト badhostname を見つけることができませんでした。名前を確認して、もう一度試してください
ExitCode : 1

ホスト: HOST2
出力: ping 要求は、ホスト badhostname を見つけることができませんでした。名前を確認して、もう一度お試しください。
終了コード: 1

于 2016-05-04T20:49:19.940 に答える
2

@jon Zの答えは良いですが、これはより簡単です:

$remotelastexitcode = invoke-command -computername localhost -ScriptBlock {
    cmd /c exit 2; $lastexitcode}

もちろん、コマンドが出力を生成する場合は、出力を抑制するか解析して終了コードを取得する必要があります。その場合、@ jon Zの回答の方が良い場合があります。

于 2015-09-16T20:03:23.773 に答える