【发布时间】:2014-10-04 09:15:22
【问题描述】:
问题
我正在从 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 句柄上使用
ps.AddCommand(script).Invoke();;我有一个泄漏或其他东西,通过两次连续调用,后者永远不会被执行。使用运行空间,它可以正常工作。
标签: c# powershell error-handling