1

I'm writing a PowerShell script to find out the session ID of the active user at a remote machine, to then launch a program using that session ID. Here is what I have so far.

$queryusers = $psexecdirectory + ' \\' +  $remotepc + ' -u ' + $domain + '\' + $username + ' -p ' + $password + ' query user'
$results = iex $queryusers

The above works fine, with the example results below being stored on the variable $results

 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
 usr1                              3  Disc         1:12  9/5/2013 11:59
AM
>usr2          rdp-tcp#1           4  Active          .  9/5/2013 11:59
AM

I've used the below to get the ID, but the number on session name 'rdp-ctp#0' changes when another user logs in, like in the output above, rendering it useless:

$id = $results | Select-String "$rdp-tcp#0\s+(\w+)" |
                 Foreach {$_.Matches[0].Groups[1].Value}

I am unfamiliar with the PowerShell syntax, and have been unable to find a site where formatting options are explained. Can someone help me out? And if you know of a website where I can learn more about extracting snippets from strings? Thanks in advance.

4

1 回答 1

3

尝试这个:

$id = $results | ? { $_ -match '(\d+)\s+Active' } | % { $matches[1] }

正则表达式(\d+)\s+Active将匹配以数字开头的关键字“Active”,随后的循环返回第一个子匹配项(即数字)。

于 2013-09-05T19:48:02.543 回答