问题
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.
回答1:
Try this:
$id = $results | ? { $_ -match '(\d+)\s+Active' } | % { $matches[1] }
The regular expression (\d+)\s+Active
will match the keyword "Active" preceeded by a number and the subsequent loop returns the first submatch (i.e. the number).
来源:https://stackoverflow.com/questions/18642355/extract-session-id-from-psexec-powershell-query-user-command