[Powershell] Install the Near Ntwork Printer as Default
#get IPScope
function GetScope{
Param([Parameter(Mandatory=$true)][string]$PC,[Parameter(Mandatory=$true)][string]$ip)
if($ip){$ipV4 = $ip}
else{$ipV4 = (Test-Connection -ComputerName $PC -Count 1 | Select IPV4Address).IPV4Address}
$ipV40 = $ipV4.split(".")[1]
$ipV41 = $ipV4.split(".")[2]
$ipV43 = $ipV4.split(".")[3]
return "$ipV40.$ipV41.$ipV42"
}
#get computer IPScope
$computerIPScope = (GetScope -PC hostname)
#All PrintServers
$PrintServersNames = Get-ADObject -Filter 'objectClass -eq "printQueue"' -Properties ShortServerName | Select-Object -ExpandProperty ShortServerName -Unique | Select-Object -Property ShortServerName
Import-Module ActiveDirectory
foreach($PrintServersName in $PrintServersNames){
$PrintServers += Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true"' `
-Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address | `
where-object {$_.Name -match $PrintServersName.ShortServerName} | `
Sort-Object -Property Operatingsystem | `
Select-Object -Property Name,IPv4Address
}
#get print server in computer's scope
[System.Collections.ArrayList]$PrintServerInfos = @()
[System.Collections.ArrayList]$PrintersInfos = @()
foreach($PrintServer in $PrintServers)
{
$PrintServerName = $PrintServer.Name
$PrintServerScope = (GetScope -ip ($PrintServer.IPv4Address))
$val = [pscustomobject]@{'Name'=$PrintServerName;'Scope'=$PrintServerScope}
$PrintServerInfos.add($val) | Out-Null
$val=$null
}
foreach($PrintServerInfo in $PrintServerInfos)
{
if($PrintServerInfo.Scope -eq $computerIPScope){$ComputerPrintServer = $PrintServerInfo.Name}
}
#get drivers of the printers in the print server $ComputerPrintServer
$Printers = Get-PrinterDriver -Name * -ComputerName $ComputerPrintServer
foreach($Printer in $Printers){
#re-install printers on the computer
Add-PrinterDriver -Name $Printer.Name
#Get Name and IP of Printers
$PrinterScope = (GetScope -PC $Printer.Name)
$val = [pscustomobject]@{'Name'=$Printer.Name;'Scope'=$PrinterScope}
$PrintersInfos.add($val) | Out-Null
$val=$null
}
#Get printer in computer's scope
foreach($PrintersInfo in $PrintersInfos)
{
if($PrintersInfo.Scope -eq $computerIPScope){$DefaultPrinter = $PrintersInfo.Name}
}
#Set this printer by default
$print = Get-CimInstance -Class Win32_Printer -Filter "Name='$DefaultPrinter'"
Invoke-CimMethod -InputObject $print -MethodName SetDefaultPrinter
Commenter cet article