Rob's Ramblings

Calling Stop-Process on a remote machine using Powershell

I decided that I wanted to update the application that I’ve been working on at work so that I can deploy it to the server much easier than copy and pasting using Explorer.  Since I have not done anything using Powershell, I thought that this would be a good opportunity.  Upon finishing my deploy scripts, I found that some files I was attempting to override or delete were locked.  After further investigation, I found that those files were being currently used.  I also found that because of th numerous times debugging, running, etc, there were hundreds of instances running (this is normal because of the nature of the application, this happens each time it runs).  So, since there is no way (that I know of) to kill lots of processes using some UI tool (Sys Internals Proc Exp or Windows Task Manager) I decided to use Powershell to do the dirty work.

So, I terminal serviced onto the server, fired up Powershell and ran the command

Stop-Process -processname "PName"

Worked great. Killed all my processes running. But I started thinking, that it would be great if my deploy script did this automatically (or at least prompted me first). Since I was running my deploy script locally but wanted to run the command remotely, I started looking into how to do this using Powershell being the newb that I am.

My first attempt was to use:

Enter-PSSession machineName



I fired up the Powershell console locally and did:

Enter-PSSession machineName
Stop-Process -processname "PName"

It worked! So, I copied this code into my .ps1 file and attempted to run it again. However, each time I ran the script, it was not finding my process when after further investigation, the process was clearly running on the remote machine. That makes no sense! How can I run it via console and then run it in a script and get 2 different results. So, I started doing some digging and came across a TechNet Forum Thread which clearly explained that using Enter-PSSession and Exit-PSSession are only for interactive use.

I knew that some Powershell commands had the -computerName parameter like Get-Process. Looking at the documentation for the Stop-Process command, there was no option to specify -computerName so I didn’t know how to proceed.

Since I can’t let things be, even though my deploy scripts work fine without doing this, I knew I had to find a way to get this to work. So after doing some more digging, I found Invoke-Command with the -computerName parameter.

To run any Powershell command on a remote machine simply do the following as an example:

Invoke-Command -computername machineName {Stop-Process -processname "ProcessName"}

Happy Coding!

February 17, 2010 Posted by | Programming | , , | 1 Comment



Get every new post delivered to your Inbox.