Home > OS >  How to get output of PowerShell's Get-WmiObject in C#
How to get output of PowerShell's Get-WmiObject in C#

Time:05-20

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#?

CodePudding user response:

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();
  • Related