Does Remoting Run Synchronously

I have a question about remoting; does stopping/starting a service on remote machines do they run synchronously? Meaning if I remotely start a service on Machine A and my code is set to next start a service remotely on Machine B; does the powershell engine wait untils the first service on Machine A is started then goes to Machine B or does it try to start them in parallel? or does it invoke the starting of the service on MachineA then proceeds to invoking the service on MachineB? Below is my code:

 $computernames = "MachineA","MachineB"
  $servicestostart = "BITS","Spooler"

  $session = New-PSSession -ComputerName $computernames -Credential mydomain\username

  #list out the sessions
  Write-Host "`nCurrent Powershell sessions:"
  Get-PSSession

  #start my services
   for($i=0; $i -lt $computernames.Count; $i++)
   {
       $currentService = $servicestostart[$i]

       $Results = Invoke-Command -Session $session[$i] -ScriptBlock{
          Start-Service -Name $Using:currentService
       }
   }

  #display the services 
 for($i=0; $i -lt $computernames.Count; $i++)
   {
         $currentService = $servicestostart[$i]

         Invoke-Command -Session $session[$i] -ScriptBlock{
          Get-Service -Name $Using:currentService
       }
   }

Remove-PSSession -Session $session
Write-Host 'Completed...'

When you run Invoke-Command, the shell will block (wait) until all computers mentioned in that Invoke-Command have either succeeded or failed. Those computers will run in parallel in a non-deterministic order, up to 32 simultaneously unless you modify -ThrottleLimit.

In your example (oh, Lord, the Write-Host pain), the “Start-Service” Invoke-Command would run for one computer at a time, in order, waiting for each one to succeed or fail before moving on to the next one. That’s because you’re manually looping through the sessions you created. Nothing will happen in parallel.

Thank you Mr. Jones for that answer. I suspected that was the case but wasn’t quite sure. Other than Write-Host; I’m assuming that Write-Output would be better?

Well, no - it’s a bit more complicated than that. For what you’re doing, you probably want Write-Verbose, and set $VerbosePrefer=“Continue” at the top of the script. Write-Output is meant for your script’s pipeline output, so it can chain up to other commands. “Learn PowerShell Toolmaking in a Month of Lunches” kind of explains the entire pattern.

Thank you. Last question, is it considered as good practice to do $VerbosePreference = “Continue” in the beginning and at the end of the script set it back to “SilentlyContinue”? and thanks for the suggested material.

You don’t need to set it back. When your script ends, the global version of the variable will take over again.