【问题标题】:C# Run Powershell command with command as parameterC# 以命令为参数运行 Powershell 命令
【发布时间】:2023-04-06 10:34:01
【问题描述】:

我想在 C# 中使用命令作为参数,但我不断收到错误消息。我需要以下 Powershell 命令:

$hg = Get-SCVMHostGroup -Name 'ClusterName'
$hp = Get-SCHardwareProfile -ID 'xxxxxxxxxxxxxxx'

Get-SCVMHostRating -VMName 'TESTVM' -CPUPriority 8 -MemoryPriority 5 -DiskPriority 3 - 
NetworkPriority 1 -DiskSpaceGB 0 -VMHostGroup $hg -HardwareProfile $hp

我尝试使用 powershell 调用前两个命令,然后将其用作参数,但随后出现错误: {“无法绑定参数'VMHostGroup'。无法将类型“Deserialized.Microsoft.SystemCenter.VirtualMachineManager.HostGroup”的值转换为类型“Microsoft.SystemCenter.VirtualMachineManager.HostGroup”。”}

代码:

            powershell = PowerShell.Create();
            powershell.Runspace = runspace;

            Command getVmHostRating = new Command("Get-SCVMHostRating");
            getVmHostRating.Parameters.Add("VMName", "TESTVM");
            getVmHostRating.Parameters.Add("CPUPriority", 8);
            getVmHostRating.Parameters.Add("MemoryPriority", 5);
            getVmHostRating.Parameters.Add("DiskPriority", 3);
            getVmHostRating.Parameters.Add("NetworkPriority", 1);
            getVmHostRating.Parameters.Add("DiskSpaceGB", 0);
            getVmHostRating.Parameters.Add("VMHostGroup", resultSCVMHostGroup);
            getVmHostRating.Parameters.Add("HardwareProfile", resultSCHardwareProfile);
            powershell.Commands.AddCommand(getVmHostRating);

            results = powershell.Invoke();

在 powershell 中,下面的代码也可以工作,所以我可以设法在 C# 中得到它,它也可以:

Get-SCVMHostRating -VMName 'TESTVM' -CPUPriority 8 -MemoryPriority 5 -DiskPriority 3 -NetworkPriority 1 -DiskSpaceGB 0 -VMHostGroup (Get-SCVMHostGroup -Name 'ClusterName') -HardwareProfile (Get-SCHardwareProfile -ID 'xxxxxxxxxxxxxxx')

任何需要的帮助

【问题讨论】:

  • resultSCVMHostGroupresultSCHardwareProfile 是从哪里来的?
  • 您好,变量(命令)已被调用,例如 resultSCVMHostGroup : // Get SCVMHost Group powershell = PowerShell.Create(); powershell.Runspace = 运行空间;命令 getSCVMHostGroup = new Command("Get-SCVMHostGroup"); getSCVMHostGroup.Parameters.Add("Name", "ClusterName"); powershell.Commands.AddCommand(getSCVMHostGroup);动态结果SCVMHostGroup = powershell.Invoke();

标签: c# powershell command hyper-v


【解决方案1】:

您可以改用AddScript()。这样您就不必在 C# 中处理获取和使用 VMHostGroup 和 SCHardwareProfile,只需让 powershell 处理它即可

string SCHardwareProfileId = "xxxxxxxxxxxxxxx";
string ClusterName = "ClusterName";
powershell.AddScript(@$"Get-SCVMHostRating -VMName 'TESTVM' -CPUPriority 8 -MemoryPriority 5 -DiskPriority 3 -NetworkPriority 1 -DiskSpaceGB 0 -VMHostGroup (Get-SCVMHostGroup -Name '{ClusterName}') -HardwareProfile (Get-SCHardwareProfile -ID '{SCHardwareProfileId}')");
results = powershell.Invoke();

【讨论】: