【发布时间】:2011-03-27 04:09:23
【问题描述】:
我有这个服务,当收到请求时,运行一个 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 的任何想法?
【问题讨论】:
标签: c# powershell