c# - 使用 System.Management.Automation 时如何访问 .NET Core 中的 CimCmdlet?
问题描述
目标
我想在 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 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 包,但这可行。
推荐阅读
- css - 在 CSS 中限制背景图像的最大宽度
- vb.net - 模拟红外遥控音量按钮
- sql - 对于 Oracle 中的每个地址更改,我应该如何处理这个开始和结束日期?
- python - Django HTML表单不填充变量
- node.js - 猫鼬在快递中使用模块导出后创建空文档
- ionic-framework - Ionic 4 PWA 和原生 android/ios 服务工作者缓存
- ios - Xcode - 已达到免费开发配置文件的最大应用程序数量(错误?)
- r - 如何使用 ggplot2 绘制时间序列数据中缺失的日期?
- c# - Exception.Data 在 C# 中可以为空吗?
- python - 如何从烧瓶中的另一个服务调用另一个服务发布方法