在 PowerShell 中解析“查询用户"的更简单方法 [英] Easier way to parse 'query user' in PowerShell

查看:65
本文介绍了在 PowerShell 中解析“查询用户"的更简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 PowerShell 中有以下查询:

I currently have the following query in PowerShell:

query user /server:$server

返回输出:

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME  
svc_chthost                               2  Disc         1:05  8/16/2016 12:01 PM  
myusername                rdp-tcp         3  Active          .  8/29/2016 11:29 AM

目前,我使用 @(query user/server:$server).Count - 1 作为表示登录用户数量的值(我知道这不太好).但是,现在我想获取诸如 USERNAMEIDLOGON TIME 之类的信息,以便在脚本的其他部分中使用.

Currently, I'm using @(query user /server:$server).Count - 1 as a value to represent the number of users logged on (it's not pretty, I know). However now I would like to obtain information such as USERNAME, ID, and LOGON TIME to use in other parts of my script.

我的问题是围绕一种更简单的方法来解析上述信息,或者可能是对我的问题的更好解决方案:计数和收集与登录用户相关的信息.

My question is surrounding an easier way to parse the information above, or maybe a better solution to my problem all together: Counting and gathering information related to logged on users.

我发现了其他似乎更有效的解决方案,但我确信必须有一种更简单的方法来完成这项任务:

I've found other solutions that seem to work better, but I'm sure there's got to be a simpler way to accomplish this task:

$ComputerName | Foreach-object { 
$Computer = $_ 
try 
    {
        $processinfo = @(Get-WmiObject -class win32_process -ComputerName $Computer -EA "Stop") 
            if ($processinfo) 
            {     
                $processinfo | Foreach-Object {$_.GetOwner().User} |  
                Where-Object {$_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"} | 
                Sort-Object -Unique | 
                ForEach-Object { New-Object psobject -Property @{Computer=$Computer;LoggedOn=$_} } |  
                Select-Object Computer,LoggedOn 
            }#If 
    } 
catch 
    { 

    }

推荐答案

评论中有很棒的参考资料,并且仍然愿意为这个问题提供更多答案,因为它应该有一个更简单的解决方案!

Awesome references in the comments, and still open to more answers for this question as it should have an easier solution!

    foreach ($s in $servers) #For Each Server
{
    foreach($ServerLine in @(query user /server:$s) -split "\n") #Each Server Line
    {
        #USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME

        $Parsed_Server = $ServerLine -split '\s+'

        $Parsed_Server[1] #USERNAME
        $Parsed_Server[2] #SESSIONNAME
        $Parsed_Server[3] #ID
        $Parsed_Server[4] #STATE
        $Parsed_Server[5] #IDLE TIME
        $Parsed_Server[6] #LOGON TIME
    }
}

这个解决方案暂时解决了这个问题,有点草率.

This solution solves the problem for now, kind of sloppy.

有关更多功能的更深入的解决方案,请查看对原始问题的评论:)

For more in-depth solutions with more functionalities, check the comments on the original question :)

这篇关于在 PowerShell 中解析“查询用户"的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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