使用 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? 的相关文章

  • Rx Framework:在超时时执行操作,而不中断原始可观察序列

    给定一个可观察的源 通过轮询低级设备的 变化 状态生成 observable source metacode IObservable
  • 使用inotify监控文件

    我正在使用 inotify 来监视本地文件 例如使用 root temp inotify add watch fd root temp mask 删除该文件后 程序将被阻止read fd buf bufSize 功能 即使我创建一个新的 r
  • C++ 中的字符串到 LPCWSTR

    我正在尝试从字符串转换为 LPCWSTR 我使用多位 1 例如 LPCWSTR ToLPCWSTR string text LPCWSTR sw LPCWSTR text c str return sw 2 返回中文字符 LPCWSTR T
  • ASP .NET MVC 5 - 客户地址一对一关系

    我在这里查看了论坛 实际上发现了一些类似的问题 但不是相同的问题 类似的解决方案没有给我正确的答案 我正在使用实体框架和代码优先方法来处理 ASP NET MVC 5 我想建立客户 gt 地址一对一关系的模型 我建模的是 客户等级 publ
  • 在 Windows 7 上安装 VS 2008 Team Developer

    有人在 Windows 7 beta 上成功安装了 VS 2008 Team Developer 版本吗 每次我尝试时 都会收到有关 C Windows Winsxs 权限不足的错误 我能够毫无问题地安装 VS 2008 Team Data
  • 实体框架 5 不清除导航属性

    我在 Entity Framework 5 中遇到了这个奇怪的问题 我在其中一个实体中有一个导航属性 我想将其设置为null 但由于某种原因 该属性只有在我第二次调用该属性时才会被清除 using var db new Entities v
  • 将 Uploadify 与 Sharepoint 和 .net 结合使用

    我在共享点页面上有一些由 JQuery 生成的 html 我想在这个 html 中使用 uploadify 将文件上传到服务器 亚历山大 https stackoverflow com users 25427 alexander gyosh
  • 如何解决素数函数的大O表示法?

    我正在尝试理解 Big O 表示法 很抱歉 如果我问的问题太明显了 但我似乎无法理解这一点 我有以下 C 代码函数 我正在尝试为其计算 Big O 表示法 for i 2 i lt 100 i for j 2 j lt i j j if i
  • 如何从c++调用python

    我是Python新手 我尝试像这样从 C 调用 python 脚本 在 Raspberry Pi 中 std string pythonCommand python Callee py a b int res system pythonCo
  • 接口中的私有成员

    是否可以在 NET 接口中创建私有成员 我听说现在可以了 但我的 IDE 拒绝了 public interface IAnimal void SetDefaultName string name ChangeName name privat
  • 为什么long long 2147483647 + 1 = -2147483648? [复制]

    这个问题在这里已经有答案了 为什么这段代码不打印相同的数字 long long a b a 2147483647 1 b 2147483648 printf lld n a printf lld n b 我知道int变量的最大数量是2147
  • 如何检查是否发生溢出? [复制]

    这个问题在这里已经有答案了 可能的重复 检测 C C 中整数溢出的最佳方法 https stackoverflow com questions 199333 best way to detect integer overflow in c
  • 将 libpng 链接到 android 原生项目

    我在尝试在本机 Android 项目中加载 libpng 时遇到问题 编译器似乎无法识别 libpng 函数 但可以识别类型 如 png byte 它可以正常编译类型 但如果我添加函数 则会抛出错误 这是编译输出 Windows 7 cmd
  • 是否可以从.NET Core中间件检索控制器的操作结果?

    public class UsersController APIControllerBase public UsersController public Client Get return new Client ClientID 1 Las
  • 正则表达式基于组的不同替换?

    所以我对正则表达式比较陌生 并且做了一些练习 我正在玩一个简单的 混淆器 它只是寻找 dot or dot or at or at 不区分大小写 并且在匹配项之前或之后有或没有任意数量的空格 这是针对通常情况的 someemail AT d
  • 为 C++ 类播种 rand()

    我正在开发一个 C 类 它使用rand 在构造函数中 我真的希望这个班级在几乎所有方面都能照顾好自己 但我不知道在哪里播种rand 如果我播种rand 在构造函数中 每次构造我的对象类型的新实例时都会对其进行播种 因此 如果我按顺序创建 3
  • TypeScript 中 C# 类虚拟成员的等效项

    因此 在 C 中 当我创建模型类和延迟加载内容时 我会执行以下操作 public int User ID get set public int Dept ID get set 然后在我的班级稍远一点的地方 我像这样弹出我的虚拟 public
  • 访问 Visual Studio 扩展中的当前代码窗格

    我正在编写一个 Visual Studio 2010 扩展 在代码视图中带有右键单击菜单 我希望能够从菜单项事件处理程序检查当前代码 但无法在对象模型中找到执行此操作的位置 如何在 Visual Studio 扩展中访问当前窗口中的代码 E
  • 为什么没有参数的函数(与实际函数定义相比)可以编译?

    我刚刚看到某人的 C 代码 我很困惑为什么要编译它 有两点我不明白 The 函数原型与实际函数定义相比没有参数 中的参数函数定义没有类型 include
  • MsBuild 在 Visual Studio Online 上找不到恢复的 NuGet 包

    我尝试构建一个存储在 Visual Studio Online 上的外部 GIT 存储库中的解决方案 它有以下步骤 1 Git 恢复 有效 2 NuGet 恢复 有效 3 构建 不起作用 查看日志时我的第一个猜测是 MsBuild 没有查找

随机推荐