PowerShell对象成员在C#

时间:2019-05-20 16:28:11

标签: c# powershell

我正在尝试从C#运行Get-NetAdapter -Physical。如果我从PS本身运行它,则结果表的InterfaceDescription和MacAddress列具有有意义的值,但是在C#中执行此操作:

using (var ps = PowerShell.Create())
{
    ps.AddCommand("Get-NetAdapter");
    ps.AddParameter("Physical");
    var results = ps.Invoke();
[...error checking here...]
    foreach (var result in results)
    {
[...null check here...]
        var name = result.Members["InterfaceDescription"].Value;
        var mac = result.Members["MacAddress"].Value;
    }
}

foreach的第二行在.Value的左侧抛出NullReferenceException。如果将Members更改为Properties,则结果相同。 name很好。我也尝试使用dynamic来吸引成员,但这似乎也不起作用。如何获得可以通过thing.MacAddress在PowerShell中获得的对象?

1 个答案:

答案 0 :(得分:2)

您正在看到这是因为“ MacAddress”是ScriptProperty:

handleCar

this answer中所述,如果仅将结果通过管道传输到Get-NetAdapter -Physical | Get-Member -Name MacAddress | fl * TypeName : Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetAdapter Name : MacAddress MemberType : ScriptProperty Definition : System.Object MacAddress {get=$out = "" if (($this.NetworkAddresses -ne $null) -and ($this.NetworkAddresses.length -ge 1)) { $MacAddress = $this.NetworkAddresses[0]; } if($MacAddress -ne $null) { for($i = 0; $i -lt $MacAddress.Length; ) { $out += $MacAddress[$i++]; if($i -eq $MacAddress.Length) { break; } $out += $MacAddress[$i++]; if ($i -lt $MacAddress.Length) { $out += '-'; } } } $out;set=param($newValue) $MacAddress = $newValue -replace '(:|-)' $this.NetworkAddresses = $MacAddress;} ,则ScriptProperty将在PowerShell运行空间中进行评估,并作为注释返回。