Powershell Trying To Restart Print Spooler

4.4k views Asked by At

I have a PowerShell script that obtains the actual name of the Windows Print Spooler

$serviceDisplayName = "Print Spooler"
$actualServiceName = (Get-Service -DisplayName "$serviceDisplayName").Name

I can find out accurately whether or not the Print Spooler is running:

Try
{
    $serviceInqResults = get-service -Name $actualServiceName -ErrorVariable err
}

Catch 
{
    write-output "An exception occurred while trying to see if $serviceDisplayName were running or not."
    write-output $err
}

But, when I try to restart the Print Spooler by either it's real name or its display name, I get the same error:

if($serviceInqResults.Status -ne "Running")
{
    write-output "The service is not running. Starting the $serviceDisplayName "

   try
   {
        Start-Service -Name $actualServiceName -ErrorVariable err
   }
    
    Catch
    {
        write-output $err
    }


Service 'Print Spooler (Spooler)' cannot be started due 
to the following error: Cannot open Spooler service on computer '.'.

I have tried starting the service with the name "Print Spooler", "Spooler", "Print Spooler (Spooler)" all with the same error, and yet I can start it in the service control manager (Services).

I am wondering what I am missing.

2

There are 2 answers

2
Lee_Dailey On BEST ANSWER

i don't understand why your code is not working. [blush] however, the following works on my win10, 20h2 install, while running elevated ...

$PrintSpooler = Get-Service -Name Spooler
$PrintSpooler

if ($PrintSpooler.Status -eq 'running')
    {
    Stop-Service -InputObject $PrintSpooler
    }

Get-Service -Name Spooler
Start-Service -Name Spooler
Get-Service -Name Spooler

output ...

Status   Name               DisplayName
------   ----               -----------
Running  Spooler            Print Spooler
Stopped  Spooler            Print Spooler
Running  Spooler            Print Spooler
1
octopusgrabbus On

Using @Lee_Dailey's example that used -InputObject, this returns Spooler, rather than Print Spooler (Thanks, Lee)

PS C:\Users\fred> Get-Service -InputObject "Print Spooler"

Status   Name               DisplayName
------   ----               -----------
Running  Spooler            Print Spooler


PS C:\Users\fred>