Skip to content

Instantly share code, notes, and snippets.

@jborean93
Created March 22, 2020 03:07
Show Gist options
  • Select an option

  • Save jborean93/00798b8781d339bfa0cb86cd20dc8e95 to your computer and use it in GitHub Desktop.

Select an option

Save jborean93/00798b8781d339bfa0cb86cd20dc8e95 to your computer and use it in GitHub Desktop.
Installs a driver from an .inf file.
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
Function Install-Driver {
<#
.SYNOPSIS
Install a driver from an .inf.
.DESCRIPTION
Long description
.PARAMETER Path
The path of the .inf driver to install. Is accepted as pipeline input by value and by property name.
.PARAMETER Force
When set the driver is installed with the DIIRFLAG_FORCE_INF flag the driver is installed on matching devices even
if the existing installed driver is a better match for the device than the one specified by -Path.
.EXAMPLE
Install-Driver -Path 'D:\amd64\w10\vioscsi.inf'
.OUTPUTS
[PSCustomObject]@{
Path - [string] - The actual path used to install the driver.
RestartNeeded = [bool] - Whether a restart was needed
}
.NOTES
You must have administrator privileges to install a driver. When running on a 64-bit OS you must be running in a
64-bit PowerShell process.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[String]
$Path,
[Switch]
$Force
)
begin {
Add-Type -Namespace Newdev -Name NativeMethods -MemberDefinition @'
[DllImport("Newdev.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool DiInstallDriverW(
IntPtr hwndParent,
string InfPath,
UInt32 Flags,
out bool NeedReboot);
'@
}
process {
try {
$flags = 0
if ($Force) {
Write-Verbose -Message "Adding DIIRFLAG_FORCE_INF flag to install"
$flags = $flags -bor 0x00000002 # DIIRFLAG_FORCE_INF
}
$restartNeeded = $false
$res = $true
if ($PSCmdlet.ShouldProcess($Path, 'Install Driver')) {
Write-Verbose -Message "Installing driver at '$Path' with the flags $flags"
$res = [Newdev.NativeMethods]::DiInstallDriverW(
[IntPtr]::Zero,
$Path,
0,
[ref]$restartNeeded
); $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Verbose -Message "DiInstallDriverW() returned $res with an error code of $err"
}
if (-not $res) {
$exp = [System.ComponentModel.Win32Exception]$err
Write-Error -Message "Failed to install driver from '$Path': $($_.Exception.Message)" -Exception $exp
return
}
[PSCustomObject]@{
Path = $Path
RestartNeeded = $restartNeeded
}
} catch {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment