How to determine the session ID on a remote computer for use with psexec -i using script / powershell / ...?

I need a script or powershell command that can determine the session ID of a specific registered user on a remote machine, which will later be used as a parameter to execute the psexec -i remote gui process on that user's session on the remote machine.

So far i have managed to use

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

To get a list of sessions on a remote computer:

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

therefore, I suppose that I can somehow isolate the desired identifier and use it, but I have not managed to do it yet

Any ideas? Maybe others are simpler ways?

Thanks for the help.

+6
scripting powershell automation psexec
source share
3 answers

In the powershell PSTerinalServices module, you can get user sessions and identifiers.
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 
+4
source share

While you are using PSExec, I will just stick with it. You can easily get an ID field with a username, for example:

 $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 running program exits.

+13
source share

This can be done without PowerShell. There is a qwinsta command line tool that comes with Windows that you can use.

Example:

 c:\>qwinsta SESSIONNAME USERNAME ID STATE TYPE DEVICE services 0 Disc console 1 Conn >rdp-tcp#0 YourUser 2 Active rdpwd rdp-tcp 65536 Listen 

Using:

 c:\>qwinsta /? Display information about Remote Desktop Sessions. QUERY SESSION [sessionname | username | sessionid] [/SERVER:servername] [/MODE] [/FLOW] [/CONNECT] [/COUNTER] [/VM] sessionname Identifies the session named sessionname. username Identifies the session with user username. sessionid Identifies the session with ID sessionid. /SERVER:servername The server to be queried (default is current). /MODE Display current line settings. /FLOW Display current flow control settings. /CONNECT Display current connect settings. /COUNTER Display current Remote Desktop Services counters information. /VM Display information about sessions within virtual machines. 
+6
source share

All Articles