如何确保已使用PowerShell停止或启动服务?

时间:2019-02-13 10:02:44

标签: c# .net powershell azure-devops

我正在VSTS/Azure DevOps管道中运行一个任务,以停止和卸载窗口服务列表。我在这里所做的是在下面的代码下运行并使用sleep方法来确保上述方法已完成。

Function DeleteService([string] $ServiceName) 
{
    TRY{

        $Service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"  

        if ($Service -ne $null) 
        {
            Write-Output "Stopping window service - '$ServiceName'"         
            $Service.StopService()     
            # Adding a sleep for ten seconds to let the process stop the service completely
            Start-Sleep -m 10000 
            Write-Output "Stopping Window service - '$ServiceName' completed"   


            Write-Output "Uninstalling window service - '$ServiceName'"         
            $Service.Delete()   
            # Adding a sleep for ten seconds to let the process stop the service completely
            Start-Sleep -m 10000
            Write-Output "Uninstalling window service - '$ServiceName' completed"   

        } 
        else 
        {
            Write-Output "Window service - '$ServiceName' does not exist. Uninstallation Complete"
        }
    }
    CATCH
    {
        $ErrorMessage = $_.Exception.Message    
        Write-Error " ********************** Error in uninstalling window service : $ServiceName with exception $ErrorMessage ********************** "
    }
}

PowerShell中没有更好的方法可以确认服务已停止,现在我可以继续了。这样我就不必在代码中放入此类补丁。

因为,正如我从Microsoft site所研究的那样,这些命令将消息发送到Windows Service Controller。他们没有完成任务。因此,我对如何编写可以按时按时执行同步运行的代码感到怀疑。

2 个答案:

答案 0 :(得分:1)

如果您使用的是PS v6,则只需使用Remove-Service,因为它将停止并删除该服务:

if (Get-Service $ServiceName -ErrorAction SilentlyContinue) {
    Remove-Service $ServiceName -Verbose
} 
else {
    Write-Output "Window service - '$ServiceName' does not exist. Uninstallation Complete"
}

如果您使用的是较低版本,则可以使用Stop-ServiceGet-CimInstance(而不是Get-WmiObject):

if (Get-Service $ServiceName -ErrorAction SilentlyContinue) {
    Stop-Service $ServiceName -Verbose
    Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'" | Remove-CimInstance
} 
else {
    Write-Output "Window service - '$ServiceName' does not exist. Uninstallation Complete"
}

答案 1 :(得分:0)

您可以使用Get-WmiObject而不是使用Get-Service并检查服务状态:

$service = Get-Service -Name 'VSS'
Write-Host $service.Status
# Stopped/Running

因此,如果要确保服务已停止然后继续删除,可以使用while循环包装状态检查。

while ($service.Status -ne 'Running')
{
  ....
}