有哪些 Powershell 命令可以安装和卸载 Windows 驱动程序?

7
注意:本问题中,“Windows驱动程序”是指 .inf 和相关文件,可以通过在Windows资源管理器中右键单击 .inf 然后单击“安装”来安装。我不是指任何可能安装驱动程序的 setup.exe 风格可执行文件。
存在以下内容:

然而,我没有找到相应的 Powershell Cmdlet 支持在 正在运行的系统中 安装和卸载驱动程序。我确定我可以用一些 PowerShell 包装 dpinst.exe,但如果存在更本地的 PowerShell 方法,则希望避免映射命令行参数和解析输出。

是否存在可在运行中的系统上安装和卸载 Windows 驱动程序的 Powershell Cmdlets?是否有其他方法使用 Powershell 安装和卸载 Windows 驱动程序,而不涉及 dpinst.exe

3个回答

6

不仅没有针对此的PowerShell cmdlet,而且在.Net框架内部似乎也没有托管代码来执行它(以下基本上是将该答案翻译成PowerShell)。

幸运的是,.Net框架可以通过平台调用(platform invoke,p/invoke)调用Windows API,而PowerShell也可以这样做。

链接的答案展示了如何在C#中执行此操作。为了在PowerShell中执行,我们将使用在该答案中生成的相同签名,并与Add-Type cmdlet(参见示例5)一起使用,以使其对您的脚本可用。

$signature = @"
[DllImport("Setupapi.dll", EntryPoint="InstallHinfSection", CallingConvention=CallingConvention.StdCall)]
public static extern void InstallHinfSection(
    [In] IntPtr hwnd,
    [In] IntPtr ModuleHandle,
    [In, MarshalAs(UnmanagedType.LPWStr)] string CmdLineBuffer,
    int nCmdShow);
"@
$Win32Functions = Add-Type -MemberDefinition $signature -UsingNamespace System.Runtime.InteropServices -Name Win32SInstallHinfSection -Namespace Win32Functions -PassThru 

$Win32Functions::InstallHinfSection([IntPtr]::Zero, [IntPtr]::Zero, "<section> <mode> <path>", 0)

请参阅安装HinfSection的MSDN文档以获取有关参数的详细信息(特别是字符串格式)。


1
InstallHinfSection 似乎具有空返回值和无返回参数。我应该期望在 PowerShell 中捕获 InstallHinfSection 可以抛出的异常吗? - alx9r
2
@alx9r 这是一个非常好的问题,不幸的是我没有答案。我建议尝试强制抛出异常,例如通过提供无效数据,然后看看它会发生什么。 - briantist
2
没有Windows API调用会生成C++异常,因为它们可能被其他语言(如C语言)调用。(猜测,如果发生错误,InstallHinfSection将向用户呈现对话框。) - Harry Johnston

3

有一个名为DeviceManagementPowerShell模块,可以通过Install-Module从PowerShell Gallery安装,其中包含Install-DeviceDriver命令。例如:

Install-Module -Name DeviceManagement -Force
Install-DeviceDriver -InfFilePath C:\Drivers\LAN\acmelan.inf
Get-Device | Where-Object Name -like 'ACME Network Adapter*' | Select-Object Name,DriverProvider,DriverVersion,DriverDescription,HasProblem

2

我必须补充说明,您可以调用 pnputil.exe 命令:

pnputil /add-driver "path\to\driver\*inf" /install

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接