【问题标题】:Powershell module loading stops in C# code when Write-Progress is used使用 Write-Progress 时,Powershell 模块加载在 C# 代码中停止
【发布时间】: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


    【解决方案1】:

    我尝试了您的代码,它可以在一个简单的控制台应用程序中运行,甚至可以在一个带有一些输出和调用Write-Progress 的简单脚本的 Windows 应用程序中运行。因此,问题不是那么容易重现...

    Powershell 类不知何故认为 这是真正的输出并完成 立即执行脚本

    嗯,也许它只是失败了,而不是“以不同的方式对待输出”,这就是输出为空的原因。执行后能检查错误集合吗?

    关于如何阻止的任何想法 写进度?

    如果你只是想阻止它,那么这应该可以工作:在调用你的工作脚本之前调用一个“配置文件”脚本,使用这个命令安装一个虚拟替换:

    function global:Write-Progress {}
    

    因此,当您的脚本调用 Write-Progress 时,实际上调用了虚拟函数 Write-Progress,这实际上“阻止了 Write-Progress”。

    【讨论】:

    • 此脚本加载 microsoft AD 模块。我没有得到任何错误,我只是得到空输出。只是远程调试它并遇到同样的问题。输出集合为空。
    • 我只是想仔细检查你的脚本没有失败。无论如何,建议的阻止 Write-Progress 的解决方案应该适合您。
    • 不是真的:(在调用import-module之前添加了功能,进度条仍然显示。
    • 您提到了“远程”(在上面的评论中)。是否在远程会话中调用了 Write-Progress?然后应在该会话中安装虚拟函数以替换可疑的 Write-Progress cmdlet。您能否提供有关您使用的场景的更多信息?到目前为止描述的场景工作得很好(嗯,对我来说)。
    • 说起来有点尴尬。此类是在服务器上运行的 Windows 服务的一部分。此外,所有 PS 脚本都在同一台服务器上。所以,通过远程说,我只是想说我还编写了一个测试程序,我可以在该服务器上使用 VS 远程调试。只是为了检查是否一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2021-09-21
    • 1970-01-01
    • 2021-06-23
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多