Powershell: Remote Execution

I am working on web application deployment using powershell, petty funny job. Mostly I need to execute powershell scripts from remote computer because server administrator do not allow me to install powershell in server and the server do no have direct access to the code repository. So normally what script do is it downloads code from version controller in local temporary folder, build it using tools and deploy it in the server from the local computer remotely.

At the time of deployment for almost every project I need to run batch/exe/msi file from remote computer and I faced various issues to do that and so sharing some of these in that blog post.

I used Windows Management Instrumentation (WMI) for the remote execution.

It is very easy to run a batch/exe/msi in a remote computer using those codes

   1: $command = "notepad.exe" 
   2: $process = [WMICLASS]"\\$serverName\ROOT\CIMV2:win32_process"
   3: $result = $process.Create($command) 

 

Codes to execute remote barch/exe/msi file with credential

   1: $cred = get-credential 
   2: $process = get-wmiobject -query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -namespace "root\cimv2" -computername $serverName -credential $cred 
   3: $results = $process.Create( "notepad.exe" )

 

But you need to give username and password in a prompt popup to continue the remote execution. Here are the codes to execute remote batch/exe/msi with username and password without popup credential window

   1: $pass = ConvertTo-SecureString -string "EnterYourPassword" -AsPlainText –Force 
   2: $cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist "domain\UserName", $pass $process = get-wmiobject -query "SELECT * FROM Meta_Class WHERE __Class = 'Win32_Process'" -namespace "root\cimv2" -computername $serverName -credential $cred 
   3: $results = $process.Create( "notepad.exe" ) 

 

Hope that post will help you to execute any remote process using powershell. By the way before executing WMI remoting be confirm that WMI is installed and running in your computer, RPC is available and firewall ports are not blocking you to execute remote process remotely.

Here is a nice example to setup WMI http://msdn.microsoft.com/en-us/library/aa389286(VS.85).aspx

3 Comments

  • Hi,

    The above article is very useful. But the problem am facing is.. I am running the command from a web application to a remote machine. Executing comand is fine, but the problem is after executing the command it is not coming out of that. Is there any work around for that.

    Please let me know.

    Thanks
    Hari Krishna.

  • I wanna copy a file from my system to remote system. please send me script

  • Very nice the part about hiding the credentials popup!

Comments have been disabled for this content.