首页 > 解决方案 > 在 Powershell 中停止服务时是否有绕过依赖服务的功能?

问题描述

我的 Powershell 代码有一些问题

我需要使用这个脚本停止和禁用一些服务但是有一些问题,这里是:

Get-Content -path $PWD\servicestop1.txt | ForEach-Object 
{
    $service = $_

    (Set-Service -Name $service -Status Stopped -StartupType Disabled -PassThru )
}

1 - 当我想停止一些服务时遇到一些依赖问题

2 - 我无法在同一个脚本中禁用和停止它们

你有什么主意吗?非常感谢!

PS:我尝试使用参数“-force”但没有用

标签: powershell

解决方案


在不知道servicestop1.txt实际持有有效服务名称的情况下,您可以尝试以下操作:

Get-Content -Path "$PWD\servicestop1.txt" | ForEach-Object {
    $service = Get-Service -Name $_ -ErrorAction SilentlyContinue
    if ($service) {
        if ($service.Status -eq 'Running') {
            # stop the service and wait for it
            $service | Stop-Service -Force
        }
        if ($service.StartType -ne 'Disabled') {
            $service | Set-Service -StartupType Disabled
        }
    }
    else {
        Write-Warning "Could not find service with name '$_'"
    }
}

推荐阅读