views:

37

answers:

2

Hello,

I am in need of a script or powershell command that will be able to determine the session id of a specific logged in user on remote machine, to be later used as parameter to the psexec -i execution of remote gui process on that session of that user on the remote machine.

So far i managed to use

psexec \\remoteMachine -u user -p pswrd query session

to get list of sessions on the remote machine:

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
console                                     0  Conn    wdcon
rdp-tcp#919       user                     1  Active  rdpwd
rdp-tcp#916       user                     3  Active  rdpwd

so i guess i could somehow isolate the needed id and use it - but haven't managed to do that yet

Any ideas? Maybe other - simpler ways?

Thanks for the help.

+2  A: 

As long as you're using PSExec, I would just stick with it. You can get the ID field pretty easily given a username e.g.:

$username = 'joe'
$results = psexec \\remoteMachine -u adminuser -p password query session
$id = $results | Select-String "$username\s+(\w+)" |
                 Foreach {$_.Matches[0].Groups[1].Value}

psexec \\remoteMachine -u $username -i $id -d notepad.exe

Note that you want to use -d with PSExec otherwise it will wait until the launched program exits.

Keith Hill
+2  A: 

With the PSTerinalServices powershell module you can get the user sessions and IDs.
The module can be found here: http://code.msdn.microsoft.com/PSTerminalServices

PS > Get-TSSession -UserName user1 -ComputerName pc1 | select UserName,SessionId

UserName SessionId
-------- ---------
User             1
Shay Levy