by Njål

TeamCity: Executing commands and programs on a remote machine using Powershell

Windows Sysinternals has a range of pretty neat tools. My favorite is PsExec – which lets me execute programs on a remote computer. It’s like Remote Desktop – but with the console. Or you could think of it as a Windows alternative of SSH – if you’re a *NIX guy.

It’s perfect when you need to restart a server where Remote Desktop Services is fubar.

 

I can execute

psexec \\myWebServer cmd.exe

and I am now running a console window on the webserver.

It is also handy when scripting/automating tasks – such as building, deploying and making backups of software projects.

But invoking PsExec from TeamCity isn’t a walk in the park, to say the least. PsExec does some funky things with the standard input/output, and invoking this from Java (which TeamCity is built on) raises all kinds of problems and stability issues.

Luckily – Powershell takes care of business.

The script below stops an IIS 7 ApplicationPool on a remote server.

[string]$HostName = “myWebServer”
[string]$Cmd = C:\Windows\System32\inetsrv\appcmd.exe stop apppool MyMainAppPool”
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ($Cmd) -ComputerName $HostName

Change $HostName and $Cmd in order to run other commands.

4 comments on “TeamCity: Executing commands and programs on a remote machine using Powershell

  1. thorhalvor on said:

    If you set up “PowerShell Remoting” then you can run all commands as if it was your own machine.
    I am not 100% sure if i am correct now. but the code you describe using Invoke-wmimethod is the IIS6-way of doing it. if you have IIS 7 and use powershell remoting then you can grab the Appool using the GET-ITEM command: “$pool = get-item iis:\….” and $pool.Stop() $pool.Start(). though, The StopStart will only recycle it, and it will start when it receives its first request. Offcourse you can do this also using PowerShell and WebClient object.

  2. Aha interesting! Will try Powershell Remoting the next time I need to do something similar.

  3. This is nice. And seems that it actually works and even returns the exit code. Is there a way to redirect the output from remote program execution?

  4. Sure thing Boris! You can use > and >> in order to redirect the output. You can probably also use the cmdlet Out-File.

    psexec \\myWebServer cmd.exe > outfile.txt
    then type “dir” + enter
    and then type “exit” + enter to exit the the shell

    You should now have a outfile.txt file on your local computer – which displays the files and folders in the c:\windows\system32\ folder on your remote server.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

52,106 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>