简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM