Powershell get a value from ‘query user’ and not the headers etc

powershell

Task, get the ID from the query user command,
I'm trying to get the ID value from the the command 'query user',

Example:PS>  query user

 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME

>administrator         rdp-tcp#0           3  Active          .  04/25/2013 08:43

I'm trying to use psexec and attach to the session.

psexec \\\pc -i sessionid somecommand

how would I go about getting the ID and only the ID from the above query?
this is what I've tried so far, among other things…

PS>  query user |Select-Object $_.ID

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME

>administrator         rdp-tcp#0           3  Active          .  04/25/2013 08:43

I would think this is easy but apparently I am having a brain fart, ideally I like to do this:

$IDValue = query user | Get_the_ID_somehow

psexec \\\pc -i $IDValue somecommand..

thanks in advance.

Best Answer

Since "query user" is not an object you cannot use it as an object in powershell unless you contruct a custom PSObject, so

$IDValue = query user | Select-Object ID
will not work.

I would use something like this:

$users = query user ;
$IDs = @() ;

for ($i=1; $i -lt $users.Count;$i++) {
  # using regex to find the IDs
  $temp = [string]($users[$i] | Select-String -pattern "\s\d+\s").Matches ;
  $temp = $temp.Trim() ;
  $IDs += $temp ;
}
Related Question