[英]powershell: Changing start type of services on a windows 7 machine
[英]Powershell - Start ordered sequence of services
我需要启动一个有序的服务序列,我需要在尝试启动下一个服务之前启动并运行每个服务,我怎样才能在 Powershell 中实现这一点? 我怎么能等到停止呢?
谢谢,
DD
请勿手动执行此操作(无论脚本语言如何)。 在服务之间定义适当的依赖关系,Windows将以正确的顺序启动/停止它们。 您可以使用sc
实用程序定义依赖项:
sc config Svc2 depend= Svc1
如果一项服务应依赖于一个以上的其他服务,则可以使用正斜杠来分隔从属服务:
sc config Svc5 depend= Svc3/Svc4
请注意, =
后面必须有一个空格,且不得在前跟一个空格。
如果您有服务名称列表(例如数组),则foreach服务:
关键可能是处理#3的所有可能性 ,包括服务失败。
但是大纲将类似于(不处理错误情况):
$serviceNames | Foreach-Object -Process {
$svc = Get-Service -Name $_
if ($svc.Status -ne 'Running') {
$svc.Start()
while ($svc.Status -ne 'Running') {
Write-Output "Waiting for $($svc.Name) to start, current status: $($svc.Status)"
Start-Sleep -seconds 5
}
}
Write-Output "$($svc.Name) is running"
}
Get-Service
返回System.ServiceProcess.ServiceController
的实例,该实例处于“活动”状态-指示服务的当前状态,而不仅是创建该实例时的状态。
类似的停止过程将用“停止”代替“运行”,用“停止”代替“开始”调用。 并且,大概颠倒了服务列表的顺序。
停止服务
$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -eq "Running")}
Foreach-Object {$_.(Stop-Service $serviceNames)}
启动服务
$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -ne "Running")}
Foreach-Object {$_.(Start-Service $ServiceNames)}
启动和等待顺序
[array]$Services = 'svc1', 'svc2', 'svc3'
$Services | foreach {
start-service $_
(get-service $_).WaitForStatus('Running')
}
可能不需要等待状态。 我没有可以测试服务速度慢的系统。
停下来按顺序等待
[array]$Services = 'svc1', 'svc2', 'svc3'
[array]::Reverse($Services)
$Services | stop-service
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.