How do I get access to CimCmdlets in .NET Core when using System.Management.Automation?

别等时光非礼了梦想. 提交于 2020-08-10 19:14:09

问题


Goal

I would like to have access to the cmdlets in the CimCmdlets module in .NET Core within C# code. Specifically, I want to be able to use the New-CimSessionOption and New-CimSession cmdlets.

NuGet Packages

Microsoft.NETCore.App v2.2.0

Microsoft.Powershell.SDK v6.2.2

Simple Demo

using System;
using System.Management.Automation;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            string str;
            using (var ps = PowerShell.Create()) {
                str = "";
                var results = ps.AddScript("Get-Command").Invoke();
                foreach (var result in results) {
                    str += result.ToString() + ", ";
                }
            }
            Console.WriteLine(str);
        }
    }
}

Output

A:, B:, C:, cd.., cd\, Clear-Host, D:, E:, F:, G:, H:, help, I:, J:, K:, L:, M:, mkdir, N:, O:, oss, P:, Pause, prompt, Q:, R:, S:, T:, TabExpansion2, U:, V:, W:, X:, Y:, Z:, Add-Content, Add-History, Add-Member, Add-Type, Clear-Content, Clear-History, Clear-Item, Clear-ItemProperty, Clear-Variable, Compare-Object, Connect-PSSession, Connect-WSMan, Convert-Path, ConvertFrom-Csv, ConvertFrom-Json, ConvertFrom-Markdown, ConvertFrom-SddlString, ConvertFrom-SecureString, ConvertFrom-StringData, ConvertTo-Csv, ConvertTo-Html, ConvertTo-Json, ConvertTo-SecureString, ConvertTo-Xml, Copy-Item, Copy-ItemProperty, Debug-Job, Debug-Process, Debug-Runspace, Disable-ExperimentalFeature, Disable-PSBreakpoint, Disable-PSRemoting, Disable-PSSessionConfiguration, Disable-RunspaceDebug, Disable-WSManCredSSP, Disconnect-PSSession, Disconnect-WSMan, Enable-ExperimentalFeature, Enable-PSBreakpoint, Enable-PSRemoting, Enable-PSSessionConfiguration, Enable-RunspaceDebug, Enable-WSManCredSSP, Enter-PSHostProcess, Enter-PSSession, Exit-PSHostProcess, Exit-PSSession, Export-Alias, Export-Clixml, Export-Csv, Export-FormatData, Export-ModuleMember, Export-PSSession, ForEach-Object, Format-Custom, Format-Hex, Format-List, Format-Table, Format-Wide, Get-Acl, Get-Alias, Get-AuthenticodeSignature, Get-ChildItem, Get-CmsMessage, Get-Command, Get-ComputerInfo, Get-Content, Get-Credential, Get-Culture, Get-Date, Get-Event, Get-EventSubscriber, Get-ExecutionPolicy, Get-ExperimentalFeature, Get-FileHash, Get-FormatData, Get-Help, Get-History, Get-Host, Get-Item, Get-ItemProperty, Get-ItemPropertyValue, Get-Job, Get-Location, Get-MarkdownOption, Get-Member, Get-Module, Get-PfxCertificate, Get-Process, Get-PSBreakpoint, Get-PSCallStack, Get-PSDrive, Get-PSHostProcessInfo, Get-PSProvider, Get-PSSession, Get-PSSessionCapability, Get-PSSessionConfiguration, Get-Random, Get-Runspace, Get-RunspaceDebug, Get-Service, Get-TimeZone, Get-TraceSource, Get-TypeData, Get-UICulture, Get-Unique, Get-Uptime, Get-Variable, Get-Verb, Get-WinEvent, Get-WSManCredSSP, Get-WSManInstance, Group-Object, Import-Alias, Import-Clixml, Import-Csv, Import-LocalizedData, Import-Module, Import-PowerShellDataFile, Import-PSSession, Invoke-Command, Invoke-Expression, Invoke-History, Invoke-Item, Invoke-RestMethod, Invoke-WebRequest, Invoke-WSManAction, Join-Path, Join-String, Measure-Command, Measure-Object, Move-Item, Move-ItemProperty, New-Alias, New-Event, New-FileCatalog, New-Guid, New-Item, New-ItemProperty, New-Module, New-ModuleManifest, New-Object, New-PSDrive, New-PSRoleCapabilityFile, New-PSSession, New-PSSessionConfigurationFile, New-PSSessionOption, New-PSTransportOption, New-Service, New-TemporaryFile, New-TimeSpan, New-Variable, New-WinEvent, New-WSManInstance, New-WSManSessionOption, Out-Default, Out-File, Out-Host, Out-Null, Out-String, Pop-Location, Protect-CmsMessage, Push-Location, Read-Host, Receive-Job, Receive-PSSession, Register-ArgumentCompleter, Register-EngineEvent, Register-ObjectEvent, Register-PSSessionConfiguration, Remove-Alias, Remove-Event, Remove-Item, Remove-ItemProperty, Remove-Job, Remove-Module, Remove-PSBreakpoint, Remove-PSDrive, Remove-PSSession, Remove-Service, Remove-TypeData, Remove-Variable, Remove-WSManInstance, Rename-Computer, Rename-Item, Rename-ItemProperty, Resolve-Path, Restart-Computer, Restart-Service, Resume-Service, Save-Help, Select-Object, Select-String, Select-Xml, Send-MailMessage, Set-Acl, Set-Alias, Set-AuthenticodeSignature, Set-Content, Set-Date, Set-ExecutionPolicy, Set-Item, Set-ItemProperty, Set-Location, Set-MarkdownOption, Set-PSBreakpoint, Set-PSDebug, Set-PSSessionConfiguration, Set-Service, Set-StrictMode, Set-TimeZone, Set-TraceSource, Set-Variable, Set-WSManInstance, Set-WSManQuickConfig, Show-Markdown, Sort-Object, Split-Path, Start-Job, Start-Process, Start-Service, Start-Sleep, Start-Transcript, Stop-Computer, Stop-Job, Stop-Process, Stop-Service, Stop-Transcript, Suspend-Service, Tee-Object, Test-Connection, Test-FileCatalog, Test-Json, Test-ModuleManifest, Test-Path, Test-PSSessionConfigurationFile, Test-WSMan, Trace-Command, Unblock-File, Unprotect-CmsMessage, Unregister-Event, Unregister-PSSessionConfiguration, Update-FormatData, Update-Help, Update-TypeData, Wait-Debugger, Wait-Event, Wait-Job, Wait-Process, Where-Object, Write-Debug, Write-Error, Write-Host, Write-Information, Write-Output, Write-Progress, Write-Verbose, Write-Warning,

C:\Program Files\dotnet\dotnet.exe (process 24268) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

Question

As you can see above in the output portion, there are no Cim cmdlets at all in the list.

Why are the cmdlets in the CimCmdlets module missing? If I download PowerShell Core and look at the available cmdlets, the CimCmdlets are indeed present. How can I get access to these CimCmdlets in .NET Core? Is there a specific NuGet package I need? Thank you for the help.


回答1:


I found a solution, albeit not a great one. I installed PowerShell Core 6.1.3 and copied the Microsoft.Management.Infrastructure.CimCmdlets.dll from the installation directory (C:\Program Files\PowerShell\6) into my project.

If I manually import this .dll before doing anything else, then these Cim cmdlets are available. For example, in my code example in the question, replace

var results = ps.AddScript("Get-Command").Invoke();

with

var results = ps.AddScript("Import-Module C:\\Microsoft.Management.Infrastructure.CimCmdlets.dll; Get-Command").Invoke()

And now the Cim cmdlets are available. I'd rather use a NuGet package, but this works.




回答2:


this free nuget package from microsoft worked for me: https://github.com/PowerShell/MMI

while it doesn't provide access to the Cim / WMIv2 powershell cmdlets, it does expose a direct api into same Cim / WMIv2 interfaces

here's a sample

try
{
    using (var session = CimSession.Create(null))
    {
        var results = session.QueryInstances(@"root\cimv2",
            "WQL",
            @"select name from win32_process where handle = 0 or handle = 4");

        foreach (var result in results)
        {
            Console.WriteLine("Process name: {0}",
            result.CimInstanceProperties["Name"].Value);
        }
    }
}
catch (CimException ex)
{
    Console.WriteLine(ex.Message);
}

full api documentation is available @https://docs.microsoft.com/en-us/dotnet/api/microsoft.management.infrastructure.cimsession?view=pscore-6.2.0)

additional context & samples are available @ https://docs.microsoft.com/en-us/windows/win32/wmisdk/enumerating-wmi#enumerating-wmi-using-c-microsoftmanagementinfrastructure



来源:https://stackoverflow.com/questions/57795873/how-do-i-get-access-to-cimcmdlets-in-net-core-when-using-system-management-auto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!