Stopping & Restarting Services Remotely Using Set-Service

前端 未结 3 1986
感动是毒
感动是毒 2021-01-12 01:19

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 s

3条回答
  •  执念已碎
    2021-01-12 01:54

    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
    

    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
    }
    

    or like this:

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

    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()
    }
    

提交回复
热议问题