ohm*_*ama 6 c# error-handling powershell
问题
我从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;
}
}
Run Code Online (Sandbox Code Playgroud)
调用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我期待失败时抛出某种异常,但它会返回0个对象.虽然HasErrors会导致知道命令是否成功; 我仍然不确定如何获得特定错误,因为没有抛出异常.
谢谢
Kei*_*ill 17
要查看错误,请查看集合PowerShell.Streams.Error或代码command.Streams.Error.
| 归档时间: |
|
| 查看次数: |
8224 次 |
| 最近记录: |