Start service remotely via script

Alex Warren 161 Reputation points
2021-08-30T21:27:10.133+00:00

Hey all,

I am trying to figure out how to start services remotely via a PS script. I have a good 40ish computers that need a service started, and I don't wanna go to each one individually. I have used ForEach scripts in the past for certian PS functions, but this is my first time messing with services, and apparantly you can't use -tosession as part of the command.

My origional script looks like this:
$computers = get-content C:\Users\user\Desktop\computers.csv

ForEach ($computer in $computers) {

$session = New-PSSession -ComputerName $computer

Set-Service -name service -StartupType Automatic -ToSession $session

} 

However, I'm getting this error:

"Set-Service : A parameter cannot be found that matches parameter name 'ToSession'."

I was thinking of piping the commands via an enter-pssession, but my last attempt at that was bad and looked like this:

enter-pssession -computername $computer | set-service -name service -startuptype automatic

Any and all help would be appreciated.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,433 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 32,526 Reputation points
    2021-08-30T22:35:16.77+00:00

    Or this...

     ForEach ($computer in $computers) {
        Set-Service -name Your-Service -StartupType Automatic -ComputerName $computer
     } 
    

    Note that the script will only configure the start type and not actually start the service. To start you need to run:

    ForEach ($computer in $computers) {
        Get-Service -name YourServiceName -ComputerName $computer | Start-Service 
     } 
    

1 additional answer

Sort by: Most helpful
  1. Andreas Baumgarten 100.3K Reputation points MVP
    2021-08-30T22:15:41.1+00:00

    Hi @Alex Warren ,

    maybe this helps:

    $Cred = Get-Credential  
    foreach ($computer in $computers) {  
        Invoke-Command -ComputerName $computer -Credential $Cred -ScriptBlock {  
            Set-Service -Name service -StartupType Automatic  
        }  
    }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments