Stopping & Restarting Services Remotely Using Set-Service

前端 未结 3 1975
感动是毒
感动是毒 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()
    }
    
    0 讨论(0)
  • 2021-01-12 02:04

    You can try this single liner command:

    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()}
    
    0 讨论(0)
  • 2021-01-12 02:12

    I am with Ansgar, this should work

    $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}
        }
    }
    

    it is a little messy but should give you a starting point

    Sorry I forgot to take time to explain what is going on, so you import each of your txt docs and then it will process for each service and each computer and restart the services.

    0 讨论(0)
提交回复
热议问题