从c#中获取Powershell错误
本文关键字:Powershell 错误 获取 | 更新日期: 2023-09-27 18:25:39
问题
我正在从c#调用powershell命令,然而,PowerShell
命令对象似乎只有属性bool HasErrors
,这并不能帮助我知道我收到了什么错误。
这就是我构建powershell命令的方式
库
public static class PowerSheller
{
public static Runspace MakeRunspace()
{
InitialSessionState session = InitialSessionState.CreateDefault();
Runspace runspace = RunspaceFactory.CreateRunspace(session);
runspace.Open();
return runspace;
}
public static PowerShell MakePowershell(Runspace runspace)
{
PowerShell command = PowerShell.Create();
command.Runspace = runspace;
return command;
}
}
调用Move-Vm cmdlet
using (Runspace runspace = PowerSheller.MakeRunspace())
{
using (PowerShell command = PowerSheller.MakePowershell(runspace))
{
command.AddCommand("Move-VM");
command.AddParameter("Name", arguments.VMName);
command.AddParameter("ComputerName", arguments.HostName);
command.AddParameter("DestinationHost", arguments.DestinationHostName);
if (arguments.MigrateStorage)
{
command.AddParameter("IncludeStorage");
command.AddParameter("DestinationStoragePath", arguments.DestinationStoragePath);
}
try
{
IEnumerable<PSObject> results = command.Invoke();
success = command.HasErrors;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
我本以为失败时会引发某种异常,但它返回了0个对象。而HasErrors
将导致知道该命令是否成功;我仍然不确定如何获得特定的错误,因为没有抛出异常。
感谢
PowerShell.Streams.Error
或代码command.Streams.Error
。
尝试迭代results
集合:
foreach (PSObject psObject in results)
{
....do stuff with psObject (output to console, etc... you can use ToString() if you want)
}
这将为您提供控制台的实际输出。