26

私の質問は、Invoke-Commandを使用してScriptBlockの戻りコードをキャプチャしようとしている点を除いて、this oneと非常によく似ています-FilePathオプション)。PowershellのInvoke-Commandで呼び出されたScriptBlockの戻り値を取得する方法

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

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

私もNew-PSSessionを使ってみましたが(これはリモートサーバ上のscript.cmdのリターンコードを見ることができます)、私はPowershellスクリプトを実際に何かするためにそれを戻す方法は見つけられません失敗。

答えて

36
$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. Zの答えは良いですが、この@ジョン、このセッションから
+0

これは機能しました。リモート変数をセッションからそのようなローカルスクリプトに戻すことができるかどうかはわかりませんでした。ありがとう! –

+6

'$ remotelastexitcode = invoke-command -ScriptBlock {cmd/c exit 2; $ lastexitcode} - セッション$ remotesessionの仕事?複数のコマンドを与えるためにセッションを使用しているので、おそらくそれを防ぐことができます。 – manojlds

+2

@manojldsはい、最初のスクリプトブロックのlastexitcodeをキャプチャすることもできます。 –

1

をlastexitcodeを取得

  • このセッションでは、あなたのscripblockを起動し、新規-PSSessionは
  • を使用して新しいセッションを作成します。簡単です:

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

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

  • +0

    これは動作しません – ajgreyling

    +0

    @ajgreyling、それは多くの情報ではありません。申し訳ありませんが、これはあなたのために働いていないようです。あなたは何を正確に見ていますか? JonZさんの答えはあなたのために働くのですか?私はただ再テストして、PS Ver 4と5で私にとってはうまくいきます。私はVer 3を手に入れることはできませんが、私は他のバージョンを探すつもりです。 – jimhark

    3
    $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を見つけることができませんでした。名前を確認して、もう一度
    終了コードを試してください:1

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

    関連する問題