0

I need to get which network interface is connected to which network. I found that this information is accessible in MSFT_NetConnectionProfile. Unfortunatelly I cannot access it directly from C# (I get ManagementException: Provider load failure on computer where it should run) but when I access it from PowerShell, it works. Then my idea is to run PowerShell command from C# but I cannot get the result.

using System.Management.Automation;

string command = "Get-WmiObject -Namespace root/StandardCimv2 -Class MSFT_NetConnectionProfile | Select-Object -Property InterfaceAlias, Name";

PowerShell psinstance = PowerShell.Create();
psinstance.Commands.AddScript(command);
var results = psinstance.Invoke();

foreach (var psObject in results)
{
    /* Get name and interfaceAlias */
}

The code runs without errors but results are empty. I tried even adding Out-File -FilePath <path-to-file> with relative and absolute file path but no file was created. I even tried old >> <path-to-file> but without luck. When I added Out-String then there was one result but it was empty string.

When I tested the commands directly in PowerShell then it worked. Is there a way how to get it in C#?

2
  • Isn't just psinstance.AddScript(command); instead of psinstance.Commands.AddScript(command); ? Commented May 17, 2022 at 14:44
  • @SantiagoSquarzon It is possible, I think that I tried both ways but both failed. Commented May 19, 2022 at 10:10

1 Answer 1

1

The PS commands must be constructed in a builder-pattern fashion. Additionally, in PS Core the Get-WmiObject has been replaced by the Get-CimInstance CmdLet.

The following snippet is working on my env:

var result = PowerShell.Create()
                       .AddCommand("Get-CimInstance")
                       .AddParameter("Namespace", "root/StandardCimv2")
                       .AddParameter("Class", "MSFT_NetConnectionProfile")
                       .Invoke();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it worked, I just had to install Microsoft.PowerShell.SDK package. Without it I got System.Management.Automation.CommandNotFoundException: The 'Get-CimInstance' command was found in the module 'CimCmdlets', but the module could not be loaded. For more information, run 'Import-Module CimCmdlets'.

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.