0

I'm trying to run Get-NetAdapter -Physical from C#. If I run it from PS itself the resulting table has InterfaceDescription and MacAddress columns with meaningful values, however doing this in 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;
    }
}

The second line in the foreach throws a NullReferenceException at the left-hand side of .Value. If I change Members to Properties the result is the same. name is fine. I've also tried using dynamic to get to the members but that doesn't seem to work either. How can I get to the object that I can obtain in PowerShell through thing.MacAddress?

1 Answer 1

2

You're seeing this because "MacAddress" is a ScriptProperty:

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;}

As described in this answer, if you just pipe the results to Select-Object *, the ScriptProperty will be evaluated in the PowerShell runspace and returned as a Note instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.