我想在我的C#代码中使用PowerCLI cmdlet。当我将-pssnapin添加到我的powershell对象然后从该管理单元执行命令时会引发异常。
这是我的代码的一部分:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VMware.Vim;
using VMware.VimAutomation.ViCore.Cmdlets;
using VMware.ImageBuilder;
using VMware.ImageBuilder.Commands;
namespace EsxImageBuilder
class Program
{
private static void Main()
{
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
using (Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfig))
{
runSpace.Open();
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.Runspace = runSpace;
powerShell.Commands.AddCommand("Add-PSSnapin").AddArgument("VMware.ImageBuilder");
powerShell.Commands.AddScript(
"Add-EsxSoftwareDepot -DepotUrl https://hostupdate.vmware.com/software/VUM/PRODUCTION/main/vmw-depot-index.xml");
IAsyncResult async = powerShell.BeginInvoke();
while (async.IsCompleted == false)
{
Thread.Sleep(1000);
Console.WriteLine("Working...");
}
Console.WriteLine("finish");
if (powerShell.Streams.Error.Count > 0)
{//Here is output of Exception
Console.WriteLine(powerShell.Streams.Error[0].ToString());
}
Console.ReadKey();
}
}
}
}
异常的输出:
'VMware.ImageBuilder.Impl.IfServer'的类型初始值设定项引发了异常。