-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNetPrinterInstall.ps1
More file actions
215 lines (188 loc) · 9.33 KB
/
NetPrinterInstall.ps1
File metadata and controls
215 lines (188 loc) · 9.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
Write-Host "NetPrinterInstall v2.0" -ForegroundColor Green
Write-Host "https://github.com/frabnet/NetPrinterInstall" -ForegroundColor Green
Write-Host "---"
Write-Host ""
$ConfigFileName = Join-Path $PSScriptRoot "NetPrinterInstallConfig.xml"
if (-not (Test-Path -Path $ConfigFileName)) {
# Config file missing; enter Setup immediately.
$Setup = $true
} else {
# Config file exists; proceed with installation
$Setup = $false
# Check for Administrator privileges; if not, auto-elevate.
$AdminRights = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $AdminRights) {
Write-Host "Restarting with Administrator rights..."
$CmdLine = "Set-Location '$($PSScriptRoot)'; .\$($MyInvocation.InvocationName) $($args)"
Start-Process powershell.exe -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", $CmdLine -Verb RunAs
Exit
}
# Now that we're running as Administrator, wait 5 seconds.
# If a key is pressed during this time, activate Setup mode.
$timeout = 5
$stopWatch = [System.Diagnostics.Stopwatch]::StartNew()
Write-Host "The new printer installation will start automatically in $timeout seconds."
Write-Host "Press any key to enter Setup (cancel the installation)."
while ($stopWatch.Elapsed.TotalSeconds -lt $timeout) {
if ([System.Console]::KeyAvailable) {
# Key pressed: read it and activate Setup.
[System.Console]::ReadKey($true) | Out-Null
$Setup = $true
break
}
Start-Sleep -Milliseconds 100
}
$stopWatch.Stop()
}
If ($Setup) {
#https://github.com/Sebazzz/PSMenu
Import-Module .\PSMenu\PSMenu.psm1
[xml]$configFile = "<?xml version=`"1.0`"?><Settings><Add><Address></Address><Name></Name><Driver></Driver><InfPath></InfPath><Default></Default><Color></Color><DuplexingMode></DuplexingMode></Add><Remove><Printer></Printer><Port></Port></Remove></Settings>"
Write-Host "This setup will generate a new configuration file."
Write-Host "Before proceeding, copy the folder containing the new printer drivers to the same location as this script."
Write-Host "After setup, running this script again will install the printer automatically."
Write-Host ""
#Find default adapater IP address (for later auto-suggestion)
$IPAddress = ( Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne "Disconnected" } | Select-Object -First 1 ).IPv4Address.IPAddress
$Bits = [System.Collections.Generic.List[System.Object]]$IPAddress.Split(".")
$Bits.RemoveAt(3)
$IPAddress = ""
$Bits | ForEach { $IPAddress += "$($_)." }
#Suggestion script block
$Suggestion = {
Start-Sleep -Milliseconds 1
$WScriptShell = New-Object -com WScript.Shell
$WScriptShell.SendKeys($args[0])
}
#Suggest ip address
Start-Job $Suggestion -ArgumentList $IPAddress | Out-Null
$configFile.Settings.Add.Address = [string](Read-Host -Prompt "Enter printer TCP/IP address")
Write-Host ""
#Search for drivers
$Drivers = @()
While ($Drivers.Count -eq 0 ) {
$searchTerm = Read-Host -Prompt "Enter a small part of the model number, then select the right driver"
Get-ChildItem -Path "*.inf" -Recurse | ForEach {
$infPath = $_.FullName | Resolve-Path -Relative
Get-Content $infPath | ForEach {
#Match a printer driver
If ( $_ -Match ('(?<=")(.*?)(?="[ =])') ) {
$Driver = $Matches.0
#Match user search
If ($Driver -match $SearchTerm) {
$Drivers += [PSCustomObject]@{
Name = $($Driver)
InfPath = $($infPath)
}
}
}
}
}
If ( $Drivers.Count -eq 0 ) {
Write-Host "No driver found for *$($SearchTerm)* in any subfolders. Please try again."
Write-Host ""
}
}
#Create menu for user selection
$MenuList = @()
$MaxLength = $Host.UI.RawUI.MaxWindowSize.Width - 55
$Drivers | ForEach {
$MenuItem = "$($_.Name) ($($_.InfPath))"
#Try to avoid Show-Menu mess with long menu entries
If ( $MenuItem.Length -gt $MaxLength ) { $MenuItem = $MenuItem.Substring( 0, $MaxLength) }
$MenuList += $MenuItem
}
$Chosen = Show-Menu -MenuItems $MenuList -ReturnIndex
$configFile.Settings.Add.Driver = [string]$Drivers[$Chosen].Name
$configFile.Settings.Add.InfPath = [string]$Drivers[$Chosen].InfPath
#Write-Host ""
#Try to clean Show-Menu mess in some conditions
$strPad = " ".PadLeft( $Host.UI.RawUI.MaxWindowSize.Width - 1 , ' ' )
Write-Host $strPad
Write-Host $strPad -NoNewline
$Host.UI.RawUI.CursorPosition = @{ x = 0; y = $Host.UI.RawUI.CursorPosition.Y }
#Get Settings.Add.Name
Start-Job $Suggestion -ArgumentList $configFile.Settings.Add.Driver | Out-Null
$configFile.Settings.Add.Name = [string](Read-Host -Prompt "Enter printer name")
Write-Host ""
#Get Settings.Add.Default
Write-Host "Do you want to set the new printer as default?"
$Chosen = Show-Menu @("No", "Yes") -ReturnIndex
$configFile.Settings.Add.Default = [string]$Chosen
Write-Host ""
Write-Host "Do you want to do any additional settings (Duplexing mode and Color)?"
Write-Host "This is not guaranteed to work with all drivers."
$Chosen = Show-Menu @("No", "Yes") -ReturnIndex
If ($Chosen) {
Write-Host ""
#Get Settings.Add.DuplexingMode
Write-Host "Please select Duplexing mode. Press ESC to skip this step."
$Chosen = Show-Menu @('OneSided','TwoSidedLongEdge','TwoSidedShortEdge')
$configFile.Settings.Add.DuplexingMode = [string]$Chosen
Write-Host ""
#Get Settings.Add.Color
Write-Host "Please select Color mode. Press ESC to skip this step."
$Chosen = Show-Menu @('Grayscale','Color') -ReturnIndex
$configFile.Settings.Add.Color = [string]$Chosen
}
Write-Host ""
Write-Host "Do you want to remove any old printers or ports?"
$Chosen = Show-Menu @("No", "Yes") -ReturnIndex
If ($Chosen) {
Write-Host ""
#Get Settings.Remove.Port
Write-Host "Enter part of the name of the PORT to remove."
Write-Host "Be more specific as possible, because ALL PORTS MATCHING PART OF THIS NAME WILL BE REMOVED."
Write-Host "Enter an empty name to skip this step"
$configFile.Settings.Remove.Port = [string](Read-Host -Prompt "Remove port")
Write-Host ""
#Get Settings.Remove.Printer
Write-Host "Enter part of the name of the PRINTER to remove."
Write-Host "Be more specific as possible, because ALL PRINTERS MATCHING PART OF THIS NAME WILL BE REMOVED."
Write-Host "Enter an empty name to skip this step"
$configFile.Settings.Remove.Printer = [string](Read-Host -Prompt "Remove printer")
}
Write-Host ""
$configFile.Save($ConfigFileName)
Write-Host -ForeGroundColor Green "Configuration file written to $($ConfigFileName)."
Write-Host ""
Write-Host "Running this script again will install the printer automatically."
Start-Sleep -Seconds 5
Exit
} Else {
[xml]$configFile = Get-Content -Path $ConfigFileName
If ($configFile.Settings.Remove.Printer -ne "") {
Get-Printer | Where Name -match $configFile.Settings.Remove.Printer | ForEach {
Write-Host "Removing printer $($_.Name)..."
Remove-Printer -Name $_.Name
}
}
If ($configFile.Settings.Remove.Port -ne "") {
Get-PrinterPort | Where Name -match $configFile.Settings.Remove.Port | ForEach {
Write-Host "Removing port $($_.Name)..."
Remove-PrinterPort -Name $_.Name
}
}
Write-Host "Installing driver..."
Start-Process -Wait -FilePath "pnputil.exe" -ArgumentList "/add-driver ""$($configFile.Settings.Add.InfPath)"" /install"
Add-PrinterDriver -Name $configFile.Settings.Add.Driver
Write-Host "Creating new port..."
Add-PrinterPort -Name "IP_$($configFile.Settings.Add.Address)" -PrinterHostAddress $configFile.Settings.Add.Address -ErrorAction SilentlyContinue
Write-Host "Installing printer..."
Add-Printer -Name $($configFile.Settings.Add.Name) -DriverName $configFile.Settings.Add.Driver -PortName "IP_$($configFile.Settings.Add.Address)"
If ($configFile.Settings.Add.Color -ne "") {
Write-Host "Configuring Color..."
Set-PrintConfiguration -PrinterName $($configFile.Settings.Add.Name) -Color ($configFile.Settings.Add.Color -eq "1")
}
If ($configFile.Settings.Add.DuplexingMode -ne "") {
Write-Host "Configuring DuplexingMode to $($configFile.Settings.Add.DuplexingMode)..."
Set-PrintConfiguration -PrinterName $($configFile.Settings.Add.Name) -DuplexingMode $configFile.Settings.Add.DuplexingMode
}
If ($configFile.Settings.Add.Default -eq "1") {
Write-Host "Setting default printer..."
(New-Object -ComObject WScript.Network).SetDefaultPrinter($($configFile.Settings.Add.Name))
}
Write-Host ""
Write-Host "Done. Closing in 5 seconds."
Start-Sleep -Seconds 5
}