使用 System.Management.Automation 时如何访问 .NET Core 中的 CimCmdlet?

2023-11-29

Goal

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

NuGet 包

微软.NETCore.App v2.2.0

微软.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);
        }
    }
}

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

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

为什么 CimCmdlets 模块中的 cmdlet 丢失?如果我下载 PowerShell Core 并查看可用的 cmdlet,就会发现 CimCmdlet 确实存在。如何在 .NET Core 中访问这些 CimCmdlet?我需要特定的 NuGet 包吗?感谢您的帮助。


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

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

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

with

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 System.Management.Automation 时如何访问 .NET Core 中的 CimCmdlet? 的相关文章

  • 确保 StreamReader 不会挂起等待数据

    下面的代码读取从 tcp 客户端流读取的所有内容 并且在下一次迭代中它将仅位于 Read 上 我假设正在等待数据 我如何确保它不会在没有任何内容可供读取时返回 我是否必须设置低超时 并在失败时响应异常 或者有更好的办法吗 TcpClient
  • 提交后禁用按钮

    当用户提交付款表单并且发布表单的代码导致 Firefox 中出现重复发布时 我试图禁用按钮 去掉代码就不会出现这个问题 在firefox以外的任何浏览器中也不会出现这个问题 知道如何防止双重帖子吗 System Text StringBui
  • 错误:表达式不产生值

    我尝试将以下 C 代码转换为 VB NET 但在编译代码时出现 表达式不产生值 错误 C Code return Fluently Configure Mappings m gt m FluentMappings AddFromAssemb
  • 如何创建包含 IPv4 地址的文本框? [复制]

    这个问题在这里已经有答案了 如何制作一个这样的文本框 我想所有的用户都见过这个并且知道它的功能 您可以使用带有 Mask 的 MaskedTestBox000 000 000 000 欲了解更多信息 请参阅文档 http msdn micr
  • 使用接口有什么好处?

    使用接口有什么用 我听说它用来代替多重继承 并且还可以用它来完成数据隐藏 还有其他优点吗 哪些地方使用了接口 程序员如何识别需要该接口 有什么区别explicit interface implementation and implicit
  • qdbusxml2cpp 未知类型

    在使用 qdbusxml2cpp 程序将以下 xml 转换为 Qt 类时 我收到此错误 qdbusxml2cpp c ObjectManager a ObjectManager ObjectManager cpp xml object ma
  • DbContext 和 ObjectContext 有什么区别

    From MSDN 表示工作单元和存储库模式的组合 使您能够查询数据库并将更改分组在一起 然后将这些更改作为一个单元写回存储 DbContext在概念上类似于ObjectContext 我虽然DbContext只处理与数据库的连接以及针对数
  • Qt - ubuntu中的串口名称

    我在 Ubuntu 上查找串行端口名称时遇到问题 如您所知 为了在 Windows 上读取串口 我们可以使用以下代码 serial gt setPortName com3 但是当我在 Ubuntu 上编译这段代码时 我无法使用这段代码 se
  • 如何在 Xaml 文本中添加电子邮件链接?

    我在 Windows Phone 8 应用程序中有一些大文本 我希望其中有电子邮件链接 例如 mailto 功能 这是代码的一部分
  • 使用自定义堆的类似 malloc 的函数

    如果我希望使用自定义预分配堆构造类似 malloc 的功能 那么 C 中最好的方法是什么 我的具体问题是 我有一个可映射 类似内存 的设备 已将其放入我的地址空间中 但我需要获得一种更灵活的方式来使用该内存来存储将随着时间的推移分配和释放的
  • 外键与独立关系 - Entity Framework 5 有改进吗?

    我读过了several http www ladislavmrnka com 2011 05 foreign key vs independent associations in ef 4 文章和问题 https stackoverflow
  • CMake 无法确定目标的链接器语言

    首先 我查看了this https stackoverflow com questions 11801186 cmake unable to determine linker language with c发帖并找不到解决我的问题的方法 我
  • 动态添加 ASP.Net 控件

    我有一个存储过程 它根据数据库中存储的记录数返回多行 现在我想有一种方法来创建 div 带有包含该行值的控件的标记 如果从数据库返回 10 行 则 10 div 必须创建标签 我有下面的代码来从数据库中获取结果 但我不知道如何从这里继续 S
  • Cmake 链接共享库:包含库中的头文件时“没有这样的文件或目录”

    我正在学习使用 CMake 构建库 构建库的代码结构如下 include Test hpp ITest hpp interface src Test cpp ITest cpp 在 CMakeLists txt 中 我用来构建库的句子是 f
  • 将 MQTTNet 服务器与 MQTT.js 客户端结合使用

    我已经启动了一个 MQTT 服务器 就像this https github com chkr1011 MQTTnet tree master例子 该代码托管在 ASP Net Core 2 0 应用程序中 但我尝试过控制台应用程序 但没有成
  • 为什么 gcc 抱怨“错误:模板参数 '0' 的类型 'intT' 取决于模板参数”?

    我的编译器是gcc 4 9 0 以下代码无法编译 template
  • 使用 C# 读取 Soap 消息

  • System.IO.FileNotFoundException:找不到网络路径。在 Windows 7 上使用 DirectoryEntry 对象时出现异常

    我正在尝试使用 DirectoryEntry 对象连接到远程 Windows 7 计算机 这是我的代码 DirectoryEntry obDirEntry new DirectoryEntry WinNT hostName hostName
  • WebSocket安全连接自签名证书

    目标是一个与用户电脑上安装的 C 应用程序交换信息的 Web 应用程序 客户端应用程序是 websocket 服务器 浏览器是 websocket 客户端 最后 用户浏览器中的 websocket 客户端通过 Angular 持久创建 并且
  • 从列表中选择项目以求和

    我有一个包含数值的项目列表 我需要使用这些项目求和 我需要你的帮助来构建这样的算法 下面是一个用 C 编写的示例 描述了我的问题 int sum 21 List

随机推荐