gpt4 book ai didi

Powershell 脚本来检查服务是否已启动,如果没有则启动它

转载 作者:行者123 更新时间:2023-12-03 12:08:57 34 4
gpt4 key购买 nike

我已经构建了一个小的 powershell 脚本来检查服务是否已启动。如果未启动,请尝试启动它,然后等待一分钟并再次检查。不断重复这个过程,直到服务成功启动。我发现循环的行为与我预期的不一样,因为我似乎必须在循环中重新分配服务变量才能获得更新的状态。这是我的代码:

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

if ($arrService.Status -ne 'Running'){
$ServiceStarted = $false}
Else{$ServiceStarted = $true}

while ($ServiceStarted -ne $true){
Start-Service $ServiceName
write-host $arrService.status
write-host 'Service started'
Start-Sleep -seconds 60
$arrService = Get-Service -Name $ServiceName #Why is this line needed?
if ($arrService.Status -eq 'Running'){
$ServiceStarted = $true}
}

如果我在没有最后第三行(带注释的那一行)的情况下运行代码,我会得到以下输出。我可以在 Windows 服务管理器中检查,并且在第一个循环后该服务显然已启动。为什么需要倒数第三行?

enter image description here

鉴于这种行为,是否有更好的方法来编写此代码?

谢谢

最佳答案

我认为您的代码可能过于复杂:如果您只是检查服务是否正在运行,如果没有,请运行它然后停止重新评估,以下内容就足够了:

Good point on the refresh .

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{

Start-Service $ServiceName
write-host $arrService.status
write-host 'Service starting'
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host 'Service is now Running'
}

}

关于Powershell 脚本来检查服务是否已启动,如果没有则启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064964/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com