我正在尝试编写一个powershell脚本:
stopped
状态,则启动它。我目前有以下内容,但在添加额外变量和if
语句时,我很糟糕。这个脚本运行得很好,但我无法重启,只有启动/停止似乎有效。
Get-Service "Print Spooler" |
Where StartTime -lt (Get-Date).AddMinutes(-60) |
Stop-Service
答案 0 :(得分:2)
我建议使用一个变量:
# for debugging
$PSDefaultParameterValues['*Service:Verbose'] = $true
$svc = Get-Service -Name Spooler
if ($svc.Status -eq 'stopped') {
$svc | Start-Service
} elseif ($svc.StartTime -lt (Get-Date).AddHours(-1)) {
$svc | Stop-Service -PassThru | Start-Service
} else {
'Print Spooler is running and StartTime is within the past hour!'
}
# other logic goes here
答案 1 :(得分:0)
StartTime
似乎不是Get-Service
在我的系统上返回的ServiceController类的属性。服务的进程ID也不是荒谬的。那令人愤慨的设计很糟糕,但事实如此。因此,我使用CIM / WMI获取进程ID以确定服务何时开始。
$Service = Get-Service "Print Spooler"
$ServiceStartTime = (Get-CimInstance -ClassName Win32_Service -Filter "Name = '$($Service.Name)'" -Property ProcessId | ForEach-Object { Get-Process -Id $_.ProcessId }).StartTime
# If services has been running for an hour, stop it
if (($Service.Status -eq 'Running') -and ($ServiceStartTime -lt (Get-Date).AddHours(-1))) {
Stop-Service $Service
}
# If service isn't running, start it
if ($Service.Status -eq 'Stopped') {
Start-Service $Service
}