我正在尝试通过我的 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/