关于这个用例有一些想法。
您可以通过几种方式获取依赖项......并根据需要启动,然后再尝试重新启动您所追求的。
# Review Dependent Services
Get-Service -Name Winmgmt -DependentServices
或者
使用 Windows PowerShell 显示服务依赖项
Get-Service -CN $env:COMPUTERNAME |
Where-Object { $_.status -eq ‘running’} |
ForEach-Object {
write-host -ForegroundColor 9 "Service name $($_.name)"
if ($_.DependentServices)
{
write-host -ForegroundColor 3 "tServices that depend on $($_.name)"
foreach ($s in $_.DependentServices)
{ "tt" + $s.name }
} #end if DependentServices
if ($_.RequiredServices)
{
Write-host -ForegroundColor 10 "tServices required by $($_.name)"
foreach ($r in $_.RequiredServices)
{ "tt" + $r.name }
} #end if DependentServices
} #end foreach-object
解决它们可以有不同的方法,这里是关于该主题的讨论。
如何通过 PowerShell 脚本重新启动具有依赖关系的服务 (128574)
# For services with just a few dependencies, running
Restart-Service winmgmt -Force -PassThru
可能就足够了,因为所有当前正在运行的依赖项都已重新启动。
但是,这是一种不安全的重启方式,因为某些服务可能先前已停止。
对于生产机器,推荐使用以下方法(示例使用 WMI 服务):
cls
Write-Host "Restarting Service with Dependencies`r`n" -f Green
# 1. Get wmi dependencies
$wmidependents = (get-service winmgmt).dependentservices
if desired to get only the running dependent services, pipe | where {$_.status -eq "running"}
# 2. Get all necessary information about dependent services
$wmidependentservices = Get-WmiObject Win32_Service |
Select-object name,state,startmode |
Where-Object {$wmidependents.name -contains $_.name}
# 3. Stop wmi dependencies
Write-Host "`r`nStopping Services`r`n-----------------`r`n" -f Yellow
ForEach ($service in $wmidependentservices)
{
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
#you can add more logic in the block
}
else
{
"$($service.name) is $($service.state) with the startmode: $($service.startmode)"
}
}
#equivalent to stop-service $wmidependents.name
# 4. Stop the WMI service
Stop-Service winmgmt -force
Write-Host "`r`nStarting Services`r`n -----------------`r`n" -f Yellow
# 5. start dependencies
ForEach ($service in $wmidependentservices)
{
Write-Host "`r`nAnalyzing $($service.name)" -f Yellow
if($service.startmode -eq "auto")
{
"Starting $($service.name)"
start-service $service.name
#you can add more logic in the block
}
else
{
"$($service.name) is $($service.state) with the startmode: $($service.startmode)"
}
}
#equivalent to start-service $wmidependents.name
# 6. start WMI
Start-Service winmgmt
请注意,WMI 将延迟自动和自动启动类型都显示为“自动”。