在c#调用powershell时使用变量

本文关键字:变量 powershell 调用 | 更新日期: 2023-09-27 18:14:37

我想检查故障转移集群上的MS服务(显示名称为'MyService'),为此我想评估c#中的powershell命令。我想到的命令是

$a = Get-ClusterResource "MyService"
$b = Get-ClusterGroup $a.OwnerGroup.Name | Get-ClusterResource | Where-Object {$_.ResourceType -eq "Network Name"}

我已经知道如何将FailoverClusters模块加载到power shell实例中。我用以下代码:

InitialSessionState state = InitialSessionState.CreateDefault();
state.ImportPSModule(new[] { "FailoverClusters" });
PowerShell ps = PowerShell.Create(state);

有了这个ps实例,我现在可以成功地执行单个集群评估命令。

现在我的理解是,如果我使用ps.AddCommand两次,首先使用Get-ClusterResource,然后使用下一行的命令,我将把Get-ClusterResource的结果管道到下一个命令中,我不想这样做,因为Get-ClusterResource-Name参数不接受管道的结果。(相反,第二行将使用AddCommand构建)

我的问题是,我如何将变量$a传递到c# powershell调用的第二行?我是否必须创建两个powershell实例并首先计算第一行,将其结果以某种方式传递给第二个调用,或者可以在编程powershell实例中定义变量?

在c#调用powershell时使用变量

我很确定您只需要在将Get-ClusterResource命令添加到管道后使用AddParameter或AddArgument。在MSDN上添加参数。

一旦您添加了第一个管道(在这种情况下只有一个命令),使用var result = ps.Invoke();,从结果中提取所需的信息。,并在添加Get-ClusterGroup

后将其用于AddParameter或AddArgument。

然后继续使用addCommand填充管道的其余部分。

Powershell Invoke方法在msdn上有一个示例

(复制粘贴以供后人使用):

// Using the PowerShell object, call the Create() method 
// to create an empty pipeline, and then call the methods  
// needed to add the commands to the pipeline. Commands 
// parameters, and arguments are added in the order that the 
// methods are called.
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process");
ps.AddArgument("wmi*");
ps.AddCommand("Sort-Object");
ps.AddParameter("descending");
ps.AddArgument("id");
Console.WriteLine("Process               Id");
Console.WriteLine("------------------------");
// Call the Invoke() method to run the commands of 
// the pipeline synchronously.
foreach (PSObject result in ps.Invoke())
{
  Console.WriteLine("{0,-20}{1}",
          result.Members["ProcessName"].Value,
          result.Members["Id"].Value);
} // End foreach.