我知道PowerShell有與Start-Job
,Wait-Job
等後臺作業的功能,但它是可以使用Process
類從System.Diagnostics
在.NET中實現同樣的事情?如果是這樣,那麼執行此操作的最佳方法是什麼?它會對運行後臺作業的默認Powershell機制有什麼優勢?使用systemdiagnostics.process運行在PowerShell中
2
後臺作業
A
回答
2
你當然可以使用Process對象爲「開始」的可執行文件異步地與你回來,你可以測試一下,看看是否EXE已完成或終止該進程的進程對象。訣竅是獲取輸出和錯誤流信息,而不會在程序運行時干擾控制檯,因此您可以執行其他操作。從MSDN文檔,它看起來像使用BeginOutputReadLine
可能做的伎倆:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
但如果你想在後臺行爲,你就需要在後臺線程執行StandardOutput.ReadToEnd(),然後創建一個機制從主控制檯線程檢索該輸出,這看起來像很多工作,現在我可以想到任何優於PowerShell後臺作業的優勢。
另一種方法是創建一個運行空間來執行bg作業,因爲此blog post by Jim Truher指出。
0
這不是優雅或有據可查。它創建一個System.Diagnostic.Process對象並對其執行一些常見的初始化。一旦獲得Process對象,您可以對其執行其他調整,然後調用Process.Start來啓動該過程。
function New-Process($cmd, $arguments, [switch]$stdout, [switch]$stdin, [switch]$stderr, [switch]$shellexec, [switch]$showwindow)
{
$process = New-Object "System.Diagnostics.Process"
$startinfo = New-Object "System.Diagnostics.ProcessStartInfo"
$startinfo.FileName = $cmd
$startinfo.Arguments = $arguments
$startinfo.WorkingDirectory = $pwd.Path
$startinfo.UseShellExecute = $shellexec
$startinfo.RedirectStandardInput = $stdin
$startinfo.RedirectStandardOutput = $stdout
$startinfo.RedirectStandardError = $stderr
if (!$showwindow) {
$startinfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
}
$process.StartInfo = $startinfo
return $process
}
相關問題
- 1. 如何在使用'使用PowerShell運行'執行PowerShell腳本時在另一個PowerShell腳本中調用函數
- 2. 使用Powershell在後臺運行函數
- 3. 使用Powershell中的參數運行TextTransform.exe
- 4. 運行命令在PowerShell中
- 5. 在PowerShell中運行EXE
- 6. 在powershell中運行nmake
- 7. 在應用程序中運行PowerShell?
- 8. 使用php運行powershell腳本
- 9. 使用PowerShell下載並運行文件
- 10. 使用vb.net參數運行powershell腳本
- 11. 使用Airflow運行.EXE和Powershell任務
- 12. 運行註冊表使用PowerShell
- 13. 使用powershell遠程運行ec2config.exe -sysprep
- 14. C#Powershell執行錯誤(腳本在Powershell中運行良好)
- 15. 在.NET 3.5運行時/庫中使用PowerShell
- 16. 在C#中使用PowerShell運行命令時訪問被拒絕
- 17. Powershell代碼在PowerShell_ise上運行良好,但在PowerShell中破解
- 18. 我如何在PowerShell中運行PowerShell中的MSBuild任務
- 19. 如何在CMD中運行PowerShell
- 20. 如何在VB.Net中運行Powershell腳本
- 21. 在PowerShell中運行一個函數
- 22. 如何在Powershell中運行Konami代碼?
- 23. 在PowerShell中運行遠程cmd命令
- 24. 在PowerShell中運行遠程腳本
- 25. 無法在Powershell中運行R.exe
- 26. 在Windows PowerShell中運行Pine/Alpine
- 27. 如何在IIS中運行PowerShell腳本?
- 28. Python不會在Windows PowerShell中運行
- 29. 在PowerShell中運行VB代碼
- 30. Git沒有在PowerShell中運行
如何執行powershell.exe來調用test1.ps1文件並將輸出轉換爲日誌? – Kiquenet 2012-09-07 08:05:19