如何在Windows PowerShell中禁用后台打印程序服务?

dkqlctbz  于 2023-01-13  发布在  Shell
关注(0)|答案(1)|浏览(153)

所以我试着写一个脚本,当后台打印服务运行时禁用它,当它不运行时启用它。每次我运行这个脚本,我都会得到这两个错误。

Stop-Service : Service 'Print Spooler (Spooler)' cannot be stopped due to the following 
error: Cannot open Spooler
service on computer '.'.
At C:\Users\pedri\Desktop\Turn On or Off Printer.ps1:8 char:2
+     Stop-Service -name "Spooler" -force
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : CloseError: 
(System.ServiceProcess.ServiceController:ServiceController) [Stop-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : 
CouldNotStopService,Microsoft.PowerShell.Commands.StopServiceCommand

Set-Service : Service 'Print Spooler (Spooler)' cannot be configured due to the 
following error: Access is denied
At C:\Users\pedri\Desktop\Turn On or Off Printer.ps1:9 char:2
+     Set-Service -name "Spooler" -startupType disabled
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : PermissionDenied: 
(System.ServiceProcess.ServiceController:ServiceController) [Set-Servi
   ce], ServiceCommandException
    + FullyQualifiedErrorId : 
CouldNotSetService,Microsoft.PowerShell.Commands.SetServiceCommand

代码:

# Get the print spooler service
$service = Get-Service -Name "Spooler"

# Check the status of the print spooler service
if ($service.Status -eq "Running") 
{
    # Disable if Service is running
    Stop-Service -name "Spooler" -force
    Set-Service -name "Spooler" -startupType "Disabled"
    Get-Service -name "Spooler"
} 
else 
{
    # Enable if Service is not running
    Start-Service -name "Spooler"
    Set-Service -name "Spooler" -startupType "Enabled"
    Get-Service -name "Spooler"
}

pause
e4yzc0pl

e4yzc0pl1#

我知道了。我只是把启用换成了手动。

# Check the status of the print spooler service
if ($service.Status -eq "Running") 
{
    $answer = Read-Host -Prompt "Will you like to disable the printers (y/n)"

    # Disable if Service is running and user says yes
    if($answer -eq "y")
    {
        Stop-Service -name "Spooler" -force
        Set-Service -name "Spooler" -startupType "Disabled"
    
    }

} 
else 
{
    $answer = Read-Host -Prompt "Will you like to enable the printers (y/n)"

    # Enable if Service is not running and user says yes
    if($answer -eq "y")
    {   
        Set-Service -name "Spooler" -status Running -startupType "Manual"
    }

}
cls
Get-Service -Name "Spooler"
echo " "
pause

相关问题