.NET Framework 4.8+PowerShell5.1下能否调用Get-WindowsDriver及实现方法
解答
可以在.NET Framework 4.8 + PowerShell 5.1环境下调用Get-WindowsDriver cmdlet,问题核心在于模块加载的架构兼容性和初始化逻辑的细节处理,以下是具体解决方案:
1. 匹配程序运行架构
DISM模块是64位专属模块,如果你的程序以32位模式运行,会无法加载系统目录下的64位DISM模块:
- 打开项目属性 → 生成 → 平台目标,选择x64
- 取消勾选"Prefer 32-bit"选项(若存在)
2. 修正模块导入逻辑
直接通过InitialSessionState预导入模块可能存在加载时机问题,建议在Runspace打开后显式执行导入操作,并添加错误捕获排查问题:
Dim state As InitialSessionState = InitialSessionState.CreateDefault() state.ExecutionPolicy = ExecutionPolicy.Unrestricted Dim runspace As Runspace = RunspaceFactory.CreateRunspace(state) runspace.Open() ' 显式导入DISM模块并捕获加载错误 Dim psImport As PowerShell = PowerShell.Create() psImport.Runspace = runspace psImport.Commands.AddScript("Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Dism\Dism.psd1 -Force -ErrorAction Stop") Try psImport.Invoke() If psImport.HadErrors Then For Each err In psImport.Streams.Error Debug.WriteLine($"模块加载错误: {err.ToString()}") Next End If Catch ex As Exception Debug.WriteLine($"导入模块异常: {ex.Message}") End Try ' 验证模块加载并执行Get-WindowsDriver Dim ps As PowerShell = PowerShell.Create() ps.Runspace = runspace ps.Commands.AddScript("Get-Module; Get-WindowsDriver -Online") For Each result As PSObject In ps.Invoke Debug.WriteLine(result.ToString()) Next result ' 清理资源 ps.Dispose() psImport.Dispose() runspace.Close() runspace.Dispose()
3. 确保运行权限与执行策略
- 程序必须以管理员权限运行,
Get-WindowsDriver需要系统级权限才能读取驱动信息 - 确认系统级PowerShell执行策略未限制(可通过管理员PowerShell执行
Get-ExecutionPolicy检查,建议设置为RemoteSigned)
4. 验证DISM模块完整性
检查C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Dism路径下的Dism.psd1、Dism.psm1等文件是否完整,若文件损坏,可从同版本Windows的正常系统中复制替换。
内容的提问来源于stack exchange,提问作者ElektroStudios
相关产品推荐
相关产品推荐

