[英]How to execute a powershell script using c# and setting execution policy?
[英]How to extract $lastexitcode from c# powershell script execution
我在這里使用代碼項目上的powershell異步執行代碼在C#中執行了Scipt:
我需要返回$ lastexitcode,Jean-Paul描述了如何使用自定義pshost類將其返回。 我在pshost中找不到返回退出代碼的任何方法或屬性。
我需要此引擎來確保腳本正確執行。
任何幫助,將不勝感激。
鮑勃。
其$ lastexitcode和$? 我需要帶回來的變量。
嗨,終於回答了。
我發現了$ host變量。 它實現了到主機的回調,特別是自定義PSHost對象,使您能夠返回$ lastexitcode。 這是對$ host的解釋的鏈接。
http://mshforfun.blogspot.com/2006/08/do-you-know-there-is-host-variable.html
像Powershell文檔一樣,它似乎是晦澀的,沒有被很好地記錄。 使用第4點,調用$ host.SetShouldExit(1)將1返回pshost的SetShouldExit方法,如此處所述。
它實際上取決於定義自己的退出代碼定義。 我猜是0和1后綴。
鮑勃。
您可以嘗試以下功能:
function run-process ($cmd, $params) {
$p = new-object System.Diagnostics.Process
$p.StartInfo = new-object System.Diagnostics.ProcessStartInfo
$exitcode = $false
$p.StartInfo.FileName = $cmd
$p.StartInfo.Arguments = $params
$p.StartInfo.UseShellExecute = $shell
$p.StartInfo.WindowStyle = 1; #hidden. Comment out this line to show output in separate console
$null = $p.Start()
$p.WaitForExit()
$exitcode = $p.ExitCode
$p.Dispose()
return $exitcode
}
希望能有所幫助
我相信您將通過使用此代碼項目來擺脫困境。 在C#中,異步執行非常容易。
PowerShell psCmd = PowerShell.Create().AddScript({Invoke-YourScriptAndReturnLastExitCode});
IAsyncResult result = psCmd.BeginInvoke();
// wait for finish
psCmd.EndInvoke(result);
另外,查看有關該項目的問題,似乎您正在嘗試在PowerShell中使用TFS。 您可以考慮以下其他信息:
希望這可以幫助
您可以編寫腳本代碼,該代碼將檢查$ lastexitcode,如果退出代碼不是您所不喜歡的代碼,則將引發異常 。
異常更容易捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.