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.



