【发布时间】:2019-02-13 10:02:44
【问题描述】:
我正在VSTS/Azure DevOps 管道中运行一个任务来停止和卸载窗口服务列表。我在这里做的是在代码下面运行并使用睡眠方法来确保上述方法已经完成。
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。他们没有完成任务。所以我很怀疑如何编写这样的代码,这些代码将与正确的准时执行同步运行。
【问题讨论】:
-
获取服务、停止服务和删除服务 (documentation link) [编辑 - PSv6 仅适用于删除服务,因此可能无济于事]
-
这些方法在移动到下一行之前是否完成了它们的工作?
-
它们是命令而不是方法,是的,它们是同步的。请注意编辑我关于 PSv6 的帖子 - 不确定您的管道支持/使用的版本。
标签: c# .net powershell azure-devops