c# - 在 C# 中并不总是看到 PowerShell 警告流的输出

标签 c# powershell

我正在尝试通过我的 C# 应用程序在 PowerShell 中运行以下命令。

PsSession.RunPowerShellScript("Get-Mailboxstatistics -Identity John.Doe");

RunPowerShellScript 方法返回输出的串联字符串,如下所示。

public static string RunPowerShellScript(string psScript)
{
    try
    {
        PowerShell ps = PowerShell.Create();
        ps.Runspace = psRunSpace; //Set Statically Elsewhere
        ps.AddScript(psScript);

        Collection<PSObject> results = ps.Invoke();

        if (ps.HadErrors)
        {
            string output = "";
            foreach (ErrorRecord errorRecord in ps.Streams.Error)
                output += errorRecord.Exception.Message.ToString();
            throw new Exception(output);
        }
        else
        {
            if (results.Count != 0)
            {
                string output = "";
                foreach (PSObject result in results)
                    output += result.BaseObject.ToString();
                return output;
            }
            else
            {
                if (ps.Streams.Warning.Count != 0)
                {
                    string output = "";
                    foreach (WarningRecord s in ps.Streams.Warning)
                        output += s.Message.ToString();
                    return output;
                }
                else
                    return "No Results.";
            }
        }
    }
    catch (Exception ex)
    {
        return "Error: " + ex.Message.ToString();
    }
}

问题是当 Get-MailboxStatistics cmdlet 返回警告时,ps.Streams.Warning.Count 仍然等于 0(实际上 所有 streams.count = 0)。

但是,如果我运行

PsSession.RunPowerShellScript("Write-Warning 'Test'")

然后它会正确返回警告(“测试”)。

我尝试通过运行这个将警告流重定向到输出流

PsSession.RunPowerShellScript("Get-Mailboxstatistics -Identity John.Doe  *>&1");

但这并不能解决问题。

如果我从 PowerShell ISE 运行 cmdlet,我会得到以下结果

PS C:\Windows\system32> Get-Mailboxstatistics -Identity John.Doe
WARNING: The user hasn't logged on to mailbox 'John.Doe'...

最佳答案

我遇到了同样的问题,我决定使用 -WarningAction Stop,然后解析异常消息。

关于c# - 在 C# 中并不总是看到 PowerShell 警告流的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987199/

相关文章:

c# - 添加类库程序集后出现 FileNotFoundException

arrays - 无法让 Powershell 提取 $StrComputer.name

.net - System.Net.ServicePointManager 单例的范围是什么

使用 $matches 数组中的值时出现 PowerShell Set-Item 奇怪现象

c# - 有没有一种简单的方法可以将命令绑定(bind)到 MVVM WPF 中的列表框?

c# - Google 电子表格查询返回空单元格

c# - 按钮应该在 C# 中引用自身

c++ - 通过 Visual C++ (API) 访问 Powershell

django - 使用特殊字符在 Heroku(通过 powershell)中设置环境变量

c# - AutoMapper 空源值和自定义类型转换器,映射失败?