【问题标题】:Stopping & Restarting Services Remotely Using Set-Service使用 Set-Service 远程停止和重启服务
【发布时间】:2019-06-13 19:51:13
【问题描述】:

我列出了 10-15 项服务,我通常需要在 6 台服务器上重新启动这些服务。我有一个脚本调用服务列表,然后调用服务器列表,然后停止所有服务:

$Services = Get-Content -Path "C:\Powershell\Services.txt"
$Machines = Get-Content -Path "C:\Powershell\Machines.txt"
Get-Service -Name $Services -ComputerName $Machines | Set-Service -Status Stopped

然后我有另一个单独的脚本来再次启动它们:

$Services = Get-Content -Path "C:\Powershell\Services.txt"
$Machines = Get-Content -Path "C:\Powershell\Machines.txt"
Get-Service -Name $Services -ComputerName $Machines | Set-Service -Status Running

我已经检查过,似乎无法找到将其放入单个脚本的方法。据我了解,Set-Service 只能停止、启动和暂停服务,而不能同时重新启动它们。

有什么想法吗?我可能遗漏了一些非常明显的东西。

【问题讨论】:

  • 是否有什么特别阻止您简单地使用Restart-Service?
  • @AnsgarWiechers -- 当我读到这篇文章时,我认为 OP 需要长时间停止服务才能执行一些需要停止服务的操作。
  • @rory.ap 即使这样你也会使用Stop-Service 和Start-Service。 Set-Service 可以(ab)用于停止和启动服务是偶然的,并且存在缺陷。

标签: powershell service


【解决方案1】:

要重启服务,只需使用Restart-Service:

$Services = Get-Content -Path "C:\Powershell\Services.txt"
$Machines = Get-Content -Path "C:\Powershell\Machines.txt"
Get-Service -Name $Services -ComputerName $Machines | Restart-Service

由于根据 cmets PowerShell v6 已从 *-Service cmdlet 中删除对远程访问的支持,因此在运行 v6 或更高版本时,您需要借助 Invoke-Command 进行远程执行,如下所示:

Invoke-Command -Computer $Machines -ScriptBlock {
    Get-Service -Name $using:Services -ErrorAction SilentlyContinue |
        Restart-Service
}

或者像这样:

Invoke-Command -Computer $Machines -ScriptBlock {
    Restart-Service $using:Services -ErrorAction SilentlyContinue
}

另一个选项是 WMI:

$fltr = ($Services | ForEach-Object { 'Name="{0}"' -f $_ }) -join ' or '
Get-WmiObject Win32_Service -Computer $Machines -Filter $fltr | ForEach-Object {
    $_.StopService()
    $_.StartService()
}

【讨论】:

  • 请注意 -ComputerName 在 PowerShell v6 中已被删除,Luke 的回答显示了它应该如何与 v6 一起使用。
【解决方案2】:

我在 Ansgar,这应该可以工作

$Services = Get-Content -Path "C:\Powershell\Services.txt"
$Machines = Get-Content -Path "C:\Powershell\Machines.txt"
foreach ($service in $services){
    foreach ($computer in $Machines){
    Invoke-Command -ComputerName $computer -ScriptBlock{
    Restart-Service -DisplayName $service}
    }
}

它有点乱,但应该给你一个起点

抱歉,我忘了花时间解释发生了什么,因此您导入了每个 txt 文档,然后它会为每个服务和每台计算机处理并重新启动服务。

【讨论】:

    【解决方案3】:

    你可以试试这个单行命令:

    Get-Content .\services.txt | %{Get-WmiObject -Class Win32_Service -ComputerName (Get-Content .\computers.txt) -Filter "Name='$_'"} | %{$_.StopService()}; Get-Content .\services.txt | %{Get-WmiObject -Class Win32_Service -ComputerName (Get-Content .\computers.txt) -Filter "Name='$_'"} | %{$_.StartService()}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2010-09-06
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      相关资源
      最近更新 更多