具有相关服务的计划任务重新启动服务

时间:2015-09-01 04:48:30

标签: windows powershell printing scheduled-tasks

我有一台充当打印服务器的Windows 2008 R2服务器。

通过重新启动Print Spooler服务,几乎解决了此服务器上出现的所有问题。

我想出了一个每晚自动重启服务的计划,我找到了这个命令:

  

Powershell.exe -ExecutionPolicy Bypass -Command {Restart-Service -Name spooler}

问题是我的假脱机程序有三个依赖它的服务,所以这个命令不起作用。在"假脱机程序"之后添加 -force 命令是否安全或者还有其他办法吗?

2 个答案:

答案 0 :(得分:3)

很好地重新启动具有依赖项的服务需要首先停止相关服务。我的Dell KB article带有示例代码。在链接腐烂的情况下,有点调整版本就是这样,

# Service to be restarted
$restartedService = "FooBar"

# Get service dependencies
$dependents = (get-service $restartedService).dependentservices  

# information about dependent services
$dependentservices = gwmi Win32_Service | Select-object name,state,startmode | ? {$dependents.name -contains $_.name}

# Stop dependencies
Write-Host "Stopping Services" -f Yellow

foreach ($service in $dependentservices){

Write-Host "`r`nAnalyzing $($service.name)" -f Yellow

    if($service.startmode -eq "auto" -or $service.status -eq "Running"){
        Write-Host "Stopping $($service.name)"
        stop-service $service.name
    } else{
        "$($service.name) is $($service.state) with the startmode: $($service.startmode)"
    }
}

# Stop the service
stop-service $restartedService -force

Write-Host "Starting Services" -f Yellow

# start dependencies
foreach ($service in $dependentservices){

    Write-Host "`r`nAnalyzing $($service.name)" -f Yellow

    if($service.startmode -eq "auto"){
        "Starting $($service.name)"
        start-service $service.name
    } else{
        "$($service.name) is $($service.state) with the startmode: $($service.startmode)"
    }
}

# start service
start-service $restartedService

答案 1 :(得分:0)

要重新启动具有依赖项的服务,在最新版本的 PowerShell(v5 及更高版本)中,您只需包含 -Force 标志。

如下面带有/不带标志的示例:

PS C:\Temp> Restart-Service -Name "nlasvc"
Restart-Service : Cannot stop service 'Network Location Awareness (nlasvc)' because it has dependent services.
It can only be stopped if the Force flag is set.
At line:1 char:1
+ Restart-Service -Name "nlasvc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Service], ServiceCommandException
+ FullyQualifiedErrorId : ServiceHasDependentServices,Microsoft.PowerShell.Commands.RestartServiceCommand

PS C:\Temp> Restart-Service -Name "nlasvc" -Force
PS C:\Temp>

并根据 Stop-ServiceRestart-Service 的 PowerShell 参考。