停止&使用 Set-Service 远程重启服务 [英] Stopping & Restarting Services Remotely Using Set-Service

查看:59
本文介绍了停止&使用 Set-Service 远程重启服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a list of 10-15 services that I routinely need to restart on 6 servers. I have a script that calls a list of services, then calls a list of the servers, and then stops all the services:

$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

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

I then have another separate script to start them up again:

$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 仅具有停止、启动和停止的能力.暂停服务,不要同时重启.

I've checked around and can't seem to find a way of putting this into a single script. As I understand, Set-Service only has the ability to Stop, Start & Pause services, not restart them at the same time.

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

Any ideas? I might be missing something completely obvious.

推荐答案

要重新启动服务,只需使用 重启服务:

To restart services simply use 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

由于根据评论 PowerShell v6 已从 *-Service cmdlet 中删除了对远程访问的支持,因此您在运行 v6 时需要求助于 Invoke-Command 进行远程执行或更新,像这样:

Since according to the comments PowerShell v6 has removed support for remote access from the *-Service cmdlets you need to resort to Invoke-Command for remote execution when running v6 or newer, like this:

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:

Another option would be WMI:

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

这篇关于停止&使用 Set-Service 远程重启服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆