[英]c# run powershell command get output as it arrives?
我希望能够从我的 c# 应用程序中运行以下 Powershell 命令并在它们到达时接收输出(进度)。
我已经尝试了一些解决方案,但我似乎无法让它们工作,或者我只是在做一些完全错误的事情..
命令是:
导入模块 AppVPkgConverter
Get-Command -Module AppVPkgConverter
ConvertFrom-AppvLegacyPackage -DestinationPath "C:\\Temp" -SourcePath "C:\\Temp2"
目前我只是在执行一个不理想的 ps1 文件,因为我看不到输出。
任何帮助或一些代码将不胜感激..
谢谢
这是一个老问题,但为了编译起见,这是我的解决方案:
using (PowerShell powerShell = PowerShell.Create()){
// Source functions.
powerShell.AddScript("Import-Module AppVPkgConverter");
powerShell.AddScript("Get-Command -Module AppVPkgConverter");
powerShell.AddScript("ConvertFrom-AppvLegacyPackage -DestinationPath "C:\Temp" -SourcePath "C:\Temp2"");
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = powerShell.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
// if null object was dumped to the pipeline during the script then a null object may be present here
if (outputItem != null)
{
Console.WriteLine($"Output line: [{outputItem}]");
}
}
// check the other output streams (for example, the error stream)
if (powerShell.Streams.Error.Count > 0)
{
// error records were written to the error stream.
// Do something with the error
}
}
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.