【问题标题】:How do I get access to CimCmdlets in .NET Core when using System.Management.Automation?使用 System.Management.Automation 时如何访问 .NET Core 中的 CimCmdlet?
【发布时间】:2020-01-07 18:56:00
【问题描述】:

目标

我想在 C# 代码中访问 .NET Core 中 CimCmdlets 模块中的 cmdlet。具体来说,我希望能够使用 New-CimSessionOption 和 New-CimSession cmdlet。

NuGet 包

Microsoft.NETCore.App v2.2.0

Microsoft.Powershell.SDK v6.2.2

简单演示

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

输出

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 . . .

问题

正如您在上面的输出部分中看到的,列表中根本没有 Cim cmdlet。

为什么缺少 CimCmdlets 模块中的 cmdlet?如果我下载 PowerShell Core 并查看可用的 cmdlet,CimCmdlet 确实存在。如何在 .NET Core 中访问这些 CimCmdlet?我需要一个特定的 NuGet 包吗?谢谢你的帮助。

【问题讨论】:

  • 你安装了powershell 6+吗?我的理解是 SDK 不是 powershell ...
  • 我确实安装了 PowerShell 6.1.3。
  • 我好像找到了解决办法。我将 PowerShell 6 安装目录中的 Microsoft.Management.Infrastructure.CimCmdlets.dll 复制到我的项目中。如果我手动导入 dll,则存在 Cim cmdlet。像这样: var results = ps.AddScript("Import-Module C:\\Microsoft.Management.Infrastructure.CimCmdlets.dll; Get-Command").Invoke();
  • 请将其添加为答案。当一个人想到它时它是有道理的......在你提到它之前,它对我来说甚至不是一个模糊的想法。 [咧嘴]
  • 好的,我添加了这个作为答案。我宁愿使用 NuGet 包,但这目前有效。感谢@Lee_Dailey 的帮助/兴趣 :)

标签: c# visual-studio powershell .net-core nuget


【解决方案1】:

我找到了一个解决方案,虽然不是很好。我安装了 PowerShell Core 6.1.3 并将 Microsoft.Management.Infrastructure.CimCmdlets.dll 从安装目录 (C:\Program Files\PowerShell\6) 复制到我的项目中。

如果我在执行任何其他操作之前手动导入此 .dll,则这些 Cim cmdlet 可用。例如,在我的问题代码示例中,替换

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

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

现在可以使用 Cim cmdlet。我宁愿使用 NuGet 包,但这可行。

【讨论】:

    【解决方案2】:

    这个来自微软的免费 nuget 包对我有用:https://github.com/PowerShell/MMI

    虽然它不提供对 Cim / WMIv2 powershell cmdlet 的访问,但它确实将直接 api 暴露到相同的 Cim / WMIv2 接口中

    这是一个示例

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

    完整的 api 文档可用@https://docs.microsoft.com/en-us/dotnet/api/microsoft.management.infrastructure.cimsession?view=pscore-6.2.0)

    其他上下文和示例可用@https://docs.microsoft.com/en-us/windows/win32/wmisdk/enumerating-wmi#enumerating-wmi-using-c-microsoftmanagementinfrastructure

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2020-03-25
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多