スキップしてメイン コンテンツに移動

投稿

1月, 2024の投稿を表示しています

PowerShellのStart-Processで起動したプロセスのExitCodeを取得する方法

PowerShellのStart-Processで起動したプロセスのExitCodeの取得方法を下記に示します。 $p = Start-Process - NoNewWindow - PassThru - FilePath "some_exe" $dummy = $p . Handle # Cache the handle $p . WaitForExit ( ) Write-Host " $p .ExitCode" 「なんでこんな単純なことを記事にするの?」と思う人もいるかもしれませんが、上記の Cache the handle の行がないと正しいExitCodeは取得できません! -Wait とかをつけてもだめです。 詳細は下記のGitHubのissueを参考にしてください。 https://github.com/PowerShell/PowerShell/issues/20400#issuecomment-1740954070

PowerShellでStart-Processで起動したアプリケーションのログをファイルとコンソールの両方に出力

はじめに PowerShell上で Start-Process コマンドを使って起動したアプリケーションは -RedirectStandardOutput や RedirectStandardError オプションを指定することで、ログを ファイルに出力 できます(コンソールには出力できないので注意)。 このログを同時にコンソールにも表示させたかったのですが、思いのほか苦戦したので備忘録として共有します。 できた方法 結局出力されたログファイルを、別起動したプロセスでTailするという方法を採用しました。 下記はsomethig.logに書き込みつつ同時にコンソールにもログの内容を出力するPowerShellの例です。 try { $logJobObj = Start-Job - ScriptBlock { Get-Content - Path ".\something.log" - Wait } $mainProcessObj = Start-Process - PassThru - FilePath process . exe - ArgumentList "-something_argument... -RedirectStandardOutput " . \something . log " RedirectStandardError " . \something . log" / / アプリケーションが終了するまで待つ While ( ! $mainProcessObj . HasExited ) { / / ログをTailしているJobの出力を受け取る Receive-Job $logJobObj / / 適当な秒数待つ Start-Sleep - Seconds 1 } Receive-Job $logJobObj } finally { if ( $logJobObj ) { Receive-Job $logJobObj / / ログをTailしているJobを終了 Stop-Job $logJobObj Re