We help IT Professionals succeed at work.
Get Started

PSSession and service-restart with a timeout

Last Modified: 2012-05-09
Hello community,

I have a script that basically does the following things.
- establish a PSSession with a remote host
- get the service status
- according to the status of the service then stop/start/kill process

My only problem is that the specific service sometimes gets stacked on the StopPending status thus my script get's stacked.  This does not happen often nevertheless it does.

Is there a way to start the stop-service scriptblock with a failed timeout or something?
For example

stop-service wait for 60seconds if it doesn't stop then do something else

this is the part of the code that is important.

$PSRemoteSession = New-PSSession -ComputerName $ServerName -Credential user1
$serviceInfo = Invoke-Command -Session $PSRemoteSession -ScriptBlock {Get-Service -Name SrvNameHere}
$serviceName = $serviceInfo.Name

switch ($serviceInfo.status) {
	'Stopped' {
		Invoke-Command -Session $PSRemoteSession -Verbose -ArgumentList $serviceName -ScriptBlock {param ($serviceName) Start-Service -Name $serviceName -Verbose}
	'StopPending' {
		Invoke-Command -Session $PSRemoteSession -Verbose -ScriptBlock {Stop-Process -Force -Name mtsrv -Confirm} Invoke-Command -Session $PSRemoteSession -Verbose -ArgumentList $serviceName -ScriptBlock {param ($serviceName) Start-Service -Name $serviceName -Verbose}
	'Running' {
	#this is the step were i would ideally start the service stop with a timeout of 60seconds.
	#if nothing happens then do something else for example kill the process and start it again.
	Invoke-Command -Session $PSRemoteSession -Verbose -ArgumentList $serviceName -ScriptBlock {param ($serviceName) Stop-Service -Name $serviceName -Force -Confirm}

 	#basicaly if the service is not stop the script keeps running for ever.

Open in new window

Any help will be much appreciated.

Watch Question
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE