Friday, July 9, 2021

Script to Stop and Disable Printer Spooler Service on Servers Not Sharing a Printer

 <#
PowerShell Script to find servers in domain that are not sharing a printer, and disable the printer spooler service on them.

Wes Brown - 7/9/2021
#>

#get servers from domain and filter out some by name

get-adcomputer -filter {name -notlike "*print*" -AND operatingsystem -like "*Server*"} -Properties operatingsystem|ForEach-Object{
$srvr = $_.dnshostname

#test connection to each server to see if it is responding
$rtn = Test-Connection -cn $_.dnshostname -count 1 -BufferSize 16 -Quiet

#log servers that are not responding
IF($rtn -match "False"){
$srvr|out-file C:\temp\spoolernoconnection.csv -Append -ErrorAction SilentlyContinue
}

ELSEIF ($rtn -match "True"){

#Check servers that respond for shared printer
$prntsrvr=Get-CimInstance -ClassName CIM_printer -ComputerName $srvr -erroraction silentlycontinue|?{$_.sharename -ne $null}

#Check servers that respond for spooler service, to include status
$prntservice=get-service -computername $srvr -name "spooler" -erroraction silentlycontinue

#If server doesn't have any shared printers, and the printer spooler is running, then stop and disable the spooler service

    IF($prntsrvr -eq $null -and $prntservice.status -eq "Running"){
        Get-Service -ComputerName $srvr -name "spooler" |stop-service -PassThru -Verbose|Set-Service -StartupType disabled -Verbose
$disabledlog = $srvr
$disabledlog|out-file C:\temp\spoolerdisable.csv -Append -ErrorAction SilentlyContinue
$prntsrvr=$null
$prntservice=$null

#Check spooler service after stop and disable command
$status = Get-Service -ComputerName $srvr -name "spooler" -erroraction SilentlyContinue|select status
$spoolerstatus = "$($srvr) , $($status)"

#Write spooler status to log file
$spoolerstatus | out-file C:\temp\spoolerstatus.csv -Append -ErrorAction SilentlyContinue
}

ELSE{
$faillog = "$($srvr) , $($prntsrvr.pscomputername) , $($prntsrvr.sharename)"
$faillog|Out-File C:\temp\spoolernoaction.csv -Append -ErrorAction SilentlyContinue
$status = Get-Service -ComputerName $srvr -name "spooler" -erroraction SilentlyContinue|select status
$spoolerstatus = "$($srvr) , $($status)"

#If a server has a shared printer, if the spooler service is disabled, log spooler status
$spoolerstatus | out-file C:\temp\spoolerstatus.csv -Append -ErrorAction SilentlyContinue
}}}