Wednesday, September 28, 2011

PsTools with Powershell - Remote Execution

So I was tasked to remote execute an exe file on a server.

I wanted to use PowerShell to do the whole thing but ended up using PsTools due to lack of time to explore PowerShell Remote.

I ran into few issue. Basically when I was executing the exe file it wasn't displaying anything to the end user. After doing some research I found that exe was running but on the wrong session. For example I wanted to see the Test.exe GUI logged in as a remote user. But when I executed the psexec it ran the Test.exe in console session id 0. My session id was 2. You can see you session by going to taskmanager and go to users tab. There you will see the session id.

In order for me to see Test.exe GUI I had to specify the session on psexec. But problem was that every time I log into remote desktop I would get a new session id.

So I googled it and found the solution for identifying the session id.

So basically psexec runs a command query session and looks for session id of the user where the app should be displayed. i.e the variable $UserSession

=======================================================================
#Make sure you change the location of PsTools exe files below
#Change following variables for your setup
set-alias psexec 'C:\PsTools\PsExec.exe
$UsersSession = 'ijaved' #Username of the user you want the app to show
$UserAdmin = 'admin' #admin user on the remote pc
$AdminPass = 'test' #pass of admin user
$RemotePc = '\\192.168.1.128' #remote pc
$App ='C:\test.exe' # App to run

#No need to change anything below
$results = & psexec '$RemotePC' -u '$UserAdmin' -p '$AdminPass' query session
$id = $results | Select-String "$UsersSession\s+(\w+)" | Foreach {$_.Matches[0].Groups[1].Value}
$delay = ping 127.0.0.1 -n 2
$call =  & psexec '$RemotePC' -u '$UserAdmin' -p '$AdminPass' -i $id -d '$App'
#End Script
=======================================================================

I found a problem where one of the installer.exe won't run even after being called. It would come up and disappear. After trying to figure out something I got my break. I found that when psexec is executing the installer it is doing so from c:\windows\system32 folder and the installer for some stupid reason was looking for its file inside system32. Don't know why but that was the case.

So I made a batch file which called the installer from its own folder. Basically batch file did the following :-

cd \
cd "c:\installerfolder\"
c:\installerfolder\install.exe

Hope it helps anyone out there.

No comments:

Post a Comment