Powershell 在本地机器上获取活动登录用户

Powershell 在本地机器上获取活动登录用户

我正在尝试获取当前登录且具有活动会话的用户。

在任务管理器中,列表很清楚地显示有两个用户会话,其中一个处于活动状态。

我想通过 Powershell 查询相同的内容。我尝试了一些可用的命令, Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique但列出的用户比我能看到的要多得多 [加入域的计算机]

我正在寻找能够提供与任务管理器完全相同的结果的查询。 在此处输入图片描述

答案1

以下是我的做法。但它不适用于 rdp 会话。

$out = query session | where {$_ -match 'console'}
$array = $out -split('\s+')
$consoleuser = $array[1]

或者:

$consoleuser = query session | select-string console | foreach { -split $_ } | 
  select -index 1

答案2

问题是Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique,它会显示所有会话,甚至包括自上次重启计算机以来已关闭的会话。遗憾的是,轮询会话的最简单方法是使用旧的可执行文件 query.exe。

您可以使用一些正则表达式将 query.exe 的输出转换为对象:

$Computer = $env:COMPUTERNAME
$Users = query user /server:$Computer 2>&1

$Users = $Users | ForEach-Object {
    (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
} | ConvertFrom-Csv

foreach ($User in $Users)
{
    [PSCustomObject]@{
        ComputerName = $Computer
        Username = $User.USERNAME
        SessionState = $User.STATE.Replace("Disc", "Disconnected")
        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
    } 
}

这将给你如下输出:

ComputerName Username SessionState SessionType
------------ -------- ------------ -----------
BSMITH-LT    bobsm    Active       console    

进一步将其转化为函数:

function Convert-QueryToObjects
{
    [CmdletBinding()]
    [Alias('QueryToObject')]
    [OutputType([PSCustomObject])]
    param
    (
        [Parameter(Mandatory = $false,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true,
                   Position = 0)]
        [Alias('ComputerName', 'Computer')]
        [string]
        $Name = $env:COMPUTERNAME
    )

    Process
    {
        Write-Verbose "Running query.exe against $Name."
        $Users = query user /server:$Name 2>&1

        if ($Users -like "*No User exists*")
        {
            # Handle no user's found returned from query.
            # Returned: 'No User exists for *'
            Write-Error "There were no users found on $Name : $Users"
            Write-Verbose "There were no users found on $Name."
        }
        elseif ($Users -like "*Error*")
        {
            # Handle errored returned by query.
            # Returned: 'Error ...<message>...'
            Write-Error "There was an error running query against $Name : $Users"
            Write-Verbose "There was an error running query against $Name."
        }
        elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
        {
            # Handdle null output called by -ErrorAction.
            Write-Verbose "Error action has supressed output from query.exe. Results were null."
        }
        else
        {
            Write-Verbose "Users found on $Name. Converting output from text."

            # Conversion logic. Handles the fact that the sessionname column may be populated or not.
            $Users = $Users | ForEach-Object {
                (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
            } | ConvertFrom-Csv

            Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

            # Output objects.
            foreach ($User in $Users)
            {
                Write-Verbose $User
                if ($VerbosePreference -eq 'Continue')
                {
                    # Add '| Out-Host' if -Verbose is tripped.
                    [PSCustomObject]@{
                        ComputerName = $Name
                        Username = $User.USERNAME
                        SessionState = $User.STATE.Replace("Disc", "Disconnected")
                        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
                    } | Out-Host
                }
                else
                {
                    # Standard output.
                    [PSCustomObject]@{
                        ComputerName = $Name
                        Username = $User.USERNAME
                        SessionState = $User.STATE.Replace("Disc", "Disconnected")
                        SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")
                    }
                }
            }
        }
    }
}

现在你可以做如下事情:Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}

答案3

可以通过以下方式实现:

get-wmiobject -Class Win32_Computersystem | select Username

答案4

有点晚了,但这就是我的做法。我从 quser 获取输出,用逗号替换制表符,然后将数据从 CSV 转换为对象。

$QUserToRichObject = ((Invoke-Expression quser) -replace '\s{2,}', ',' | ConvertFrom-Csv)

If($QUserToRichObject){

    $UserSessions = @()

    ForEach($Record in $QUserToRichObject){

        # If the active session, remove the '>' character from Username value
        If($Record.USERNAME -Like ">*"){$Record.USERNAME = ($Record.USERNAME -Replace ">", "")}

        $UserSessions += @{
            Username        = [string]$Record.USERNAME
            SessionName     = [string]$Record.SESSIONNAME
            ID              = [string]$Record.ID
            State           = [string]$Record.STATE
            Idle            = [string]$Record.'IDLE TIME'
            LogonTime       = [string]$Record.'LOGON TIME'
        }
    }
}

$UserSessions

<#
Outputs:
Name                           Value                                                                                                                                                                           
----                           -----                                                                                                                                                                           
ID                             1                                                                                                                                                                               
SessionName                    console                                                                                                                                                                         
Idle                           none                                                                                                                                                                            
LogonTime                      04/11/2019 14:01                                                                                                                                                                
Username                       SomeUsername                                                                                                                                                                 
State                          Active
#>

相关内容