我一直在玩我在这里找到的剧本......这是一个非常优雅的剧本。但是,每次我尝试修改它以执行多个服务的停止/启动时,我都会打破它。没有个人列出每一个。有任何想法吗?这是启动/停止服务的脚本。
$SvcName
需要阅读这些服务:ftSysPolicy
,ftSysInventory
,ftSysAlarm
,ftSysSSN
,ftSysRpcProv
,ftSysEService
, ftSysRAS
,ftSysMad
#Change these values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'localhost'
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (Get-Service -ComputerName $SvrName -Name $SvcName)
Write-Host "$SvcName on $SvrName is $($svc.status)"
switch ($svc.Status) {
'Stopped' {
Write-Host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-Host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-Host "$SvcName is $($svc.Status). Taking no action."
}
}
if ($WaitForIt -ne "") {
try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt, '00:02:00')
} catch {
Write-Host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (Get-Service -ComputerName $SvrName -Name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-Host "$Result`: $SvcName on $SvrName is $($svc.Status)"
}
答案 0 :(得分:2)
创建一个服务名称数组并循环重新启动它们的逻辑:
$svcs = @('ftSysPolicy', 'ftSysInventory', 'ftSysAlarm', 'ftSysSSN', 'ftSysRpcProv', 'ftSysEService', 'ftSysRAS', 'ftSysMad')
foreach (svcName in $svcs) {
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$SvcName is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (get-service -computername $SvrName -name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}
}
或者,甚至更好,将逻辑放入一个函数并调用它。
另外,请查看get-service
,stop-service
和start-service
cmdlet