[英]Getting Write-Progress -PercentComplete status from within C#
[英]Powershell module loading stops in C# code when Write-Progress is used
我有这项服务,当收到请求时,它将运行powershell命令并返回结果。 这是调用程序的类代码:
public class PowerShellScript {
public PowerShellScript() {
}
public Object[] Invoke( String strScriptName, NameValueCollection nvcParams ) {
Boolean bResult = true;
int n = 0;
Object[] objResult = null;
PowerShell ps = PowerShell.Create();
String strScript = strScriptName;
for (n = 0; n < nvcParams.Count; n++) {
strScript += String.Format( " -{0} {1}", nvcParams.GetKey( n ), nvcParams[n] );
}
//ps.AddScript( @"E:\snapins\Init-profile.ps1" );
ps.AddScript( strScript );
Collection<PSObject> colpsOutput = ps.Invoke();
if (colpsOutput.Count > 0)
objResult = new Object[colpsOutput.Count];
n = 0;
foreach (PSObject psOutput in colpsOutput) {
if (psOutput != null) {
try {
objResult[n] = psOutput.BaseObject;
}
catch (Exception ex) {
//exception should be handeled properly in powershell script
}
}
n++;
}
colpsOutput.Clear();
ps.Dispose();
return objResult;
}
}
方法调用返回powershell脚本返回的所有结果。 但是,问题在于,如果被调用的脚本在导入的模块或脚本本身中包含Write-Progress,则Powershell类会以某种方式认为这是真实输出,并立即完成脚本执行,因此返回null作为对象。
理想情况下,可以使用Out-Null cmdlet阻止输出,但不适用于Write-Progress。 关于如何阻止Write-Progress的任何想法?
我尝试了您的代码,它在一个普通的控制台应用程序中甚至在带有简单脚本的Windows应用程序中都可以正常工作,该脚本具有一些输出和Write-Progress
调用。 因此,问题不是那么容易重现。
Powershell类以某种方式认为这是真实的输出并立即完成脚本执行
嗯,也许只是失败了,而不是“不同地对待输出”,这就是为什么输出为空的原因。 执行后可以检查错误收集吗?
关于如何阻止Write-Progress的任何想法?
如果您只是要阻止它,那么它应该可以工作:在调用您的工作程序脚本之前,请使用此命令安装一个虚拟替换来调用“配置文件”脚本:
function global:Write-Progress {}
因此,当您的脚本调用Write-Progress
,实际上会调用伪函数Write-Progress
,这实际上有效地“阻止了Write-Progress”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.