从 psexec/PowerShell 查询用户命令中提取会话 ID [英] Extract session ID from psexec / PowerShell query user command

查看:63
本文介绍了从 psexec/PowerShell 查询用户命令中提取会话 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PowerShell 脚本来找出远程计算机上活动用户的会话 ID,然后使用该会话 ID 启动程序.这是我目前所拥有的.

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

以上工作正常,下面的示例结果存储在变量 $results

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

我使用下面的来获取 ID,但是当另一个用户登录时,会话名称rdp-ctp#0"上的数字会发生变化,就像上面的输出一样,使其变得无用:

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}

我不熟悉 PowerShell 语法,并且无法找到解释格式选项的站点.有人可以帮我吗?如果您知道一个网站,我可以在其中了解有关从字符串中提取片段的更多信息?提前致谢.

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.

推荐答案

试试这个:

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

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

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).

这篇关于从 psexec/PowerShell 查询用户命令中提取会话 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆