Interacting with Get-WmiObject via .NET core

1.6k Views Asked by At

I need to get information about system. I can get it from Get-WmiObject with Powershell. But I need to gather it with .NET core application.

I'm able to execute some basic commands like Get-Command or Get-Process.

When i try to exexute Get-WmiObject, i have this error

The term 'Get-WmiObject' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Same issue with this command using (Get-CIMInstance CIM_ComputerSystem).Name

The term 'Get-CIMInstance' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Do you know a workaround to execute Get-CIMInstance or Get-WmiObjet with dotnet core using powershell ?

Update

private PSDataCollection<PSObject> InvokeScript(string script)
{

    using (PowerShell ps = PowerShell.Create())
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        ps.Runspace = runspace;

        ps.AddScript(script);

        ps.Streams.Error.DataAdded += Error_DataAdded;

        PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
        outputCollection.DataAdded += OutputCollection_DataAdded;

        var result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);

        foreach (var item in ps.Streams.Error)
        {
            _logger.LogError(item.ToString());
        }

        _logger.LogInformation("Execution has stopped. Execution state: " + ps.InvocationStateInfo.State);

        return outputCollection;
    }
}

When i invoke the script Get-Command, i found in the result, Get-WmiObject. But when i invoke Get-WmiObject, that doesn't run !

0

There are 0 best solutions below