问题描述
问题
我正在从c#调用powershell命令,但 PowerShell
命令对象似乎仅具有属性 bool HasErrors
,这无法帮助我知道我收到的什么错误。
I am invoking powershell commands from c# however, the PowerShell
command object only seems to have the property bool HasErrors
which doesn't help me know what error I received.
这就是我构建Powershell命令的方式
This is how I build my powershell command
库
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
将导致知道命令是否成功;我仍然不确定如何获取特定错误,因为不会引发异常。
I was expecting some sort of exception to be thrown on failure, but instead it returns 0 objects. While HasErrors
will result in knowing if the command was successful or not; I'm still not sure how to get the specific error, as no exception is thrown.
谢谢
推荐答案
要查看错误,请查看集合 PowerShell.Streams.Error
或代码 command.Streams。错误
。
To see the errors look at the collection PowerShell.Streams.Error
or in your code command.Streams.Error
.
这篇关于从C#获取Powershell错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!