等待状态服务 PowerShell

3
我已经编写了一个脚本来停止任何服务器上的服务!但是我遇到了错误:
      YMethod invocation failed because[System.ServiceProcess.ServiceControllerStatus] does not contain a method   named 'WaitForStatus'.
    At C:\Admin\Scripts\JBoss_StartStopp\stoppa_alla_IX2 och IX3.ps1:18 char:7
    +       $getservicestatus.WaitForStatus("Stopped")
    +       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

当您在服务器上退出服务时,我希望等待服务停止后再转到下一个服务器上的下一个服务!
   $serverlist = Get-Content “.\server.txt”
   $servicename = "JBoss_cambio"

   $serverlistIX3 = Get-Content “.\ix3.txt”
   $servicenameIX3 = "Laskopia_Cosmic"


  foreach ($server in $serverlist) {

$getservicestatus = (Get-Service -Name $servicename -ComputerName $server).status
if ($getservicestatus -eq "Running") {
  Set-Service -Name $servicename -ComputerName $server -Status Stopped

  $getservicestatusIX3.WaitForStatus("Stopped")

  Write-Host "$server $servicename Stoppad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicename var redan Stopped!" -ForegroundColor Yellow
  }
}


   foreach ($server in $serverlistIX3) {

$getservicestatusIX3 = (Get-Service -Name $servicenameIX3 -ComputerName $server).status
if ($getservicestatusIX3 -eq "Running") {
  Set-Service -Name $servicenameIX3 -ComputerName $server -Status Stopped
  $getservicestatusIX3.WaitForStatus("Stopped")
  Write-Host "$server $servicenameIX3 Sttopad!" -ForegroundColor Green
  }
else
  {
  Write-Host "$server $servicenameIX3 var redan Stoppad!" -ForegroundColor Yellow
  }
}


    Write-Host "." -ForegroundColor DarkBlue
     Read-Host "Tryck ENTER för att avsluta"
3个回答

10
WaitForStatus 方法是 System.ServiceProcess.ServiceController 类的成员,而不是 ServiceControllerStatus。例如:

$s = Get-Service spooler
$s.WaitForStatus("Stopped")

你可以将你的代码修改为如下:

$serviceIX3 = Get-Service -Name $servicenameIX3 -ComputerName $server
if($serviceIX3.status -eq "Running") {
    Stop-Service $serviceIX3
    $serviceIX3.WaitForStatus("Stopped")
    Write-Host "$server $servicenameIX3 Sttopad!" -ForegroundColor Green
}

我该如何知道它在检查状态直到停止?!我想看到它等待停止状态。 - Am Ba
1
你是对的。已编辑代码使用 Stop-Service - Janne Tuukkanen
你是什么意思?! - Am Ba
建议使用服务状态枚举而不是字符串字面量(“Stopped”): [System.ServiceProcess.ServiceControllerStatus] :: Stopped - galaxis

2
您的$getservicestatus是一个System.ServiceProcess.ServiceControllerStatus,而不是ServiceController对象。

这个getservicestatus没有WaitForStatus方法。

请尝试以下操作:

$getservice = Get-Service -Name $servicename -ComputerName $server

现在,您可以使用$getservices.WaitForStatus("Stopped")
Write-Output "We stop the service: $servicename"
Stop-Service -Name $servicename
$getservice.WaitForStatus("Stopped")
Write-Output "$servicename Stoped"

我怎样才能看到它在检查状态直到停止?!我想看到它等待停止状态。 - Am Ba

0

除非您使用时间跨度参数,否则等待将持续每1/4秒左右进行测试,并可能无意中永久等待。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接