我编写了一个脚本,告诉我文件中列出的所有计算机的SEP Master Service是否正在运行,如果停止,则启动该服务,并让我知道它是否不存在。它似乎可以启动服务,但是我在查看每台计算机上状态的输出时遇到了问题。如果该服务正在列表中的每台计算机上运行,它将显示输出正常。如果其中一台计算机没有运行该服务,则会启动它,但是对于已经运行了该服务的计算机,我看不到第一条if语句的写输出消息。我希望看到的输出是显示所有正在运行服务的计算机的运行状态,在停止服务的计算机上启动服务时的输出,并且希望看到消息告诉我该服务不在哪些计算机上。
$computers = Get-Content -Path "C:\temp2\generic_service2.bat"
$serivce = Get-Service -name SepMasterService -computername $computer
foreach ($computer in $computers) {
$ServiceStatus = $serivce.Status
$ServiceDisplayName = $serivce.DisplayName
if ($ServiceStatus -eq 'Running') {
Write-Output "Service OK - Status of $ServiceDisplayName is $ServiceStatus on $computer"
}
elseif ($ServiceStatus -eq 'stopped') {
Start-Service -Name SepMasterService -PassThru
}
else {
Write-Output "Service doesn't exist"
}
}
第2行上的变量拼写为$serivce
。尽管这不会影响脚本的工作,但最好的做法是不要在代码中留下类似的内容。它完全要求其他人陪伴并只在一个位置“修复”它,然后您的脚本中断。
而且,我猜想这行属于inside foreach而不是外部?
由于语句的顺序,如果在检查时服务正在运行,则只会看到Service OK
消息。如果在elseif
中启动它,则它在测试时是not启动的,因此从代码中可以预期,如果必须重新启动它,则不会看到任何内容写入屏幕。如果要在重新启动时将某些内容写入屏幕,请在Start-Service
之后添加它,如下所示:
if ($ServiceStatus -eq 'Running') {
Write-Output "Service OK - Status of $ServiceDisplayName is $ServiceStatus on $computer"
}
elseif ($ServiceStatus -eq 'stopped') {
Start-Service -Name SepMasterService -PassThru
Write-Output "Whatever you want to see when you restart the service"
}
else {
Write-Output "Service doesn't exist"
}