Stop-Service on a remote machine takes a long time

Hi All,

I have a very simple script that stops a service on a list of remote machines. I know the service will not stop straight away as there are a number of processes that continue to run for up to an hour.
How do I ignore the ‘warning : Waiting for service…’ and move on to the next machine in the list?

 [CmdletBinding()]
    Param(
        [Parameter(valuefrompipeline=$true)]
        [alias("cn")]
        [string[]]$ComputerName=($servername.keys | %{if($servername.$_  -eq $env:computername){$_}})
        )
        Begin
        {
         "Preparing to stop service..."
        }
        Process
        {
            foreach($computer in $ComputerName){
            $Server= $($serverName[$($Computer)]) 
            Write-Host -ForegroundColor Yellow "Processing: $ComputerName  System Name: $Server"
            try
            {
              Invoke-Command -ComputerName $Server { Stop-Service -DisplayName "GEO*" -Confirm} -ErrorAction stop
             }
            Catch
            {
                Write-Host -ForegroundColor red "An error occured executing the command."
                $errorMessage = $_.Exception.Message
                Write-Host $errorMessage
                
            }
            }
            }
        End
        {
        }

Thanks

Hi Mark,

You can add the switch -AsJob to Invoke-Command and use the construct Get-Job | Wait-Job to wait for the completion of all jobs before exiting the function/script.

    [CmdletBinding()]
    Param(
        [Parameter(valuefrompipeline=$true)]
        [alias('cn')]
        [string[]]$ComputerName=($servername.keys | %{if($servername.$_  -eq $env:computername){$_}})
        )
        Begin
        {
            'Preparing to stop service...'
        }
        Process
        {
            foreach($computer in $ComputerName){
                $Server= $($serverName[$($Computer)]) 
                Write-Host -ForegroundColor Yellow "Processing: $ComputerName  System Name: $Server"
                try
                {
                    Invoke-Command -ComputerName $Server { Stop-Service -DisplayName 'GEO*' -Confirm} -ErrorAction stop -AsJob
                }
                Catch
                {
                    Write-Host -ForegroundColor red 'An error occured executing the command.'
                    $errorMessage = $_.Exception.Message
                    Write-Host $errorMessage
                
                }
            }
            
        }
        End
        {
            Get-Job | Wait-Job
        }

I hope that helps.

Regards,
Daniel

Works perfectly,

Many thanks