如何使用管道将Powershell代码转换为c#代码

本文关键字:代码 转换 Powershell 何使用 管道 | 更新日期: 2023-09-27 18:12:48

下面是我在Powershell中使用的代码:

get-vm -computername CN | select -ExpandProperty networkadapters | select macaddress, ipaddresses | Select-string -pattern "some mac"

这是我目前在c#中所做的:

public static string GetIPFromMac(string mac, string Server) 
{
    Command command1 = new Command("get-vm");
    command1.Parameters.Add("ComputerName", Server);
    Command command = new Command("select");
    command.Parameters.Add("ExpandProperty", "networkadapter");
    Command command3 = new Command("select");
    command3.Parameters.Add("macaddress");
    command3.Parameters.Add("ipaddresses");
    Command command4 = new Command("select-string");
    command4.Parameters.Add("pattern", mac.Replace("-", ""));
    string ip = string.Empty;
    using(Pipeline hostPipeline = GetRunspace().CreatePipeline()) 
    {
        hostPipeline.Commands.Add(command1);
        hostPipeline.Commands.Add(command);
        hostPipeline.Commands.Add(command3);
        hostPipeline.Commands.Add(command4);
        ip = hostPipeline.Invoke()[0].ToString().Trim().Split(new []{' '})[1];
        hostPipeline.Stop();
    }
    return ip;
}

在这行中,我得到了下一个错误:

ip = hostPipeline.Invoke()[0].ToString().Trim().Split(new char[] { ' ' })[1];
错误:

类型的未处理异常"System.Management.Automation。ParameterBindingException发生在System.Management.Automation.dll

我认为问题在于我阅读两个"Select"命令的方式,所以我的问题是我该如何解决这个问题?

如何使用管道将Powershell代码转换为c#代码

更改以下行:

Command command3 = new Command("select");
command3.Parameters.Add("macaddress");
command3.Parameters.Add("ipaddresses");

Command command3 = new Command("select");
command3.Parameters.Add("Property", new string[] { "macaddress", "ipaddresses" });