我知道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