Powershell Get Active logged in user in local machine





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







3















I am trying to get currently logged in users who has active session.



In the task manager, the list is crystal clear that there are two user sessions and one is active.



I want to query the same via Powershell.
I tried few of the available commands
Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique which lists lot more users than I can even see [domain joined computer]



I am looking for the query which can give results exactly like Task Manager.
enter image description here










share|improve this question























  • What about query user?

    – duenni
    Mar 8 '17 at 15:55











  • @duenni seems right way. anyway to parse and get Active users. Seems like it's string output

    – Reddy
    Mar 8 '17 at 15:57











  • Maybe this can help you superuser.com/q/587737/378809

    – duenni
    Mar 8 '17 at 16:03











  • AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

    – Ƭᴇcʜιᴇ007
    Mar 8 '17 at 18:13













  • @MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

    – Reddy
    Mar 9 '17 at 6:07


















3















I am trying to get currently logged in users who has active session.



In the task manager, the list is crystal clear that there are two user sessions and one is active.



I want to query the same via Powershell.
I tried few of the available commands
Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique which lists lot more users than I can even see [domain joined computer]



I am looking for the query which can give results exactly like Task Manager.
enter image description here










share|improve this question























  • What about query user?

    – duenni
    Mar 8 '17 at 15:55











  • @duenni seems right way. anyway to parse and get Active users. Seems like it's string output

    – Reddy
    Mar 8 '17 at 15:57











  • Maybe this can help you superuser.com/q/587737/378809

    – duenni
    Mar 8 '17 at 16:03











  • AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

    – Ƭᴇcʜιᴇ007
    Mar 8 '17 at 18:13













  • @MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

    – Reddy
    Mar 9 '17 at 6:07














3












3








3








I am trying to get currently logged in users who has active session.



In the task manager, the list is crystal clear that there are two user sessions and one is active.



I want to query the same via Powershell.
I tried few of the available commands
Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique which lists lot more users than I can even see [domain joined computer]



I am looking for the query which can give results exactly like Task Manager.
enter image description here










share|improve this question














I am trying to get currently logged in users who has active session.



In the task manager, the list is crystal clear that there are two user sessions and one is active.



I want to query the same via Powershell.
I tried few of the available commands
Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique which lists lot more users than I can even see [domain joined computer]



I am looking for the query which can give results exactly like Task Manager.
enter image description here







windows powershell users






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 '17 at 15:44









ReddyReddy

2663618




2663618













  • What about query user?

    – duenni
    Mar 8 '17 at 15:55











  • @duenni seems right way. anyway to parse and get Active users. Seems like it's string output

    – Reddy
    Mar 8 '17 at 15:57











  • Maybe this can help you superuser.com/q/587737/378809

    – duenni
    Mar 8 '17 at 16:03











  • AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

    – Ƭᴇcʜιᴇ007
    Mar 8 '17 at 18:13













  • @MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

    – Reddy
    Mar 9 '17 at 6:07



















  • What about query user?

    – duenni
    Mar 8 '17 at 15:55











  • @duenni seems right way. anyway to parse and get Active users. Seems like it's string output

    – Reddy
    Mar 8 '17 at 15:57











  • Maybe this can help you superuser.com/q/587737/378809

    – duenni
    Mar 8 '17 at 16:03











  • AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

    – Ƭᴇcʜιᴇ007
    Mar 8 '17 at 18:13













  • @MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

    – Reddy
    Mar 9 '17 at 6:07

















What about query user?

– duenni
Mar 8 '17 at 15:55





What about query user?

– duenni
Mar 8 '17 at 15:55













@duenni seems right way. anyway to parse and get Active users. Seems like it's string output

– Reddy
Mar 8 '17 at 15:57





@duenni seems right way. anyway to parse and get Active users. Seems like it's string output

– Reddy
Mar 8 '17 at 15:57













Maybe this can help you superuser.com/q/587737/378809

– duenni
Mar 8 '17 at 16:03





Maybe this can help you superuser.com/q/587737/378809

– duenni
Mar 8 '17 at 16:03













AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

– Ƭᴇcʜιᴇ007
Mar 8 '17 at 18:13







AFAIK there isn't a native way via PowerShell, I've looked for it in the past. See Powershell get a value from 'query user' and not the headers etc

– Ƭᴇcʜιᴇ007
Mar 8 '17 at 18:13















@MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

– Reddy
Mar 9 '17 at 6:07





@MagicallyDelicous, I am actually trying to execute some scripts in remote machine using remote powershell. If there's no active user, I am trying to reboot the machine.

– Reddy
Mar 9 '17 at 6:07










3 Answers
3






active

oldest

votes


















3














The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.



You can convert the output of query.exe to objects using a bit of regex:



$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]+", "")
}
}


Which will give you output like this:



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


Taking it a lot further in to a function:



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]+", "")
}
}
}
}
}
}


and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}






share|improve this answer


























  • the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

    – Reddy
    Mar 13 '17 at 2:27











  • You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

    – omniomi
    Mar 13 '17 at 13:30





















1














Here's how I do it. It doesn't work for rdp sessions though.



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


Or:



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





share|improve this answer

































    -1














    this can be done with:




    get-wmiobject -Class Win32_Computersystem | select Username




    regards






    share|improve this answer
























    • It gives me empty result when I execute in remote machine from RDP :(

      – Reddy
      Mar 8 '17 at 15:51






    • 1





      the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

      – s0mm3r
      Mar 8 '17 at 16:04














    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "3"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1186568%2fpowershell-get-active-logged-in-user-in-local-machine%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.



    You can convert the output of query.exe to objects using a bit of regex:



    $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]+", "")
    }
    }


    Which will give you output like this:



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


    Taking it a lot further in to a function:



    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]+", "")
    }
    }
    }
    }
    }
    }


    and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}






    share|improve this answer


























    • the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

      – Reddy
      Mar 13 '17 at 2:27











    • You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

      – omniomi
      Mar 13 '17 at 13:30


















    3














    The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.



    You can convert the output of query.exe to objects using a bit of regex:



    $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]+", "")
    }
    }


    Which will give you output like this:



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


    Taking it a lot further in to a function:



    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]+", "")
    }
    }
    }
    }
    }
    }


    and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}






    share|improve this answer


























    • the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

      – Reddy
      Mar 13 '17 at 2:27











    • You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

      – omniomi
      Mar 13 '17 at 13:30
















    3












    3








    3







    The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.



    You can convert the output of query.exe to objects using a bit of regex:



    $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]+", "")
    }
    }


    Which will give you output like this:



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


    Taking it a lot further in to a function:



    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]+", "")
    }
    }
    }
    }
    }
    }


    and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}






    share|improve this answer















    The issue with Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique is that it shows all sessions even those that have been closed since the last time the computer rebooted. The easiest way to poll sessions is unfortunately using the old executable query.exe.



    You can convert the output of query.exe to objects using a bit of regex:



    $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]+", "")
    }
    }


    Which will give you output like this:



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


    Taking it a lot further in to a function:



    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]+", "")
    }
    }
    }
    }
    }
    }


    and now you can do things like: Get-ADComputer -Filter {Name -like "SERVER*"} | Convert-QueryToObjects | ? {$_.SessionState -eq 'Active'}







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 10 '17 at 14:18

























    answered Mar 10 '17 at 14:12









    omniomiomniomi

    617




    617













    • the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

      – Reddy
      Mar 13 '17 at 2:27











    • You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

      – omniomi
      Mar 13 '17 at 13:30





















    • the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

      – Reddy
      Mar 13 '17 at 2:27











    • You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

      – omniomi
      Mar 13 '17 at 13:30



















    the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

    – Reddy
    Mar 13 '17 at 2:27





    the only problem is. The quser returns output in local language. This will be a problem if one wants to run on remote machines which might has different lang

    – Reddy
    Mar 13 '17 at 2:27













    You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

    – omniomi
    Mar 13 '17 at 13:30







    You can modify the function to handle different languages but there sadly no real alternative ways to get the information you need. The only viable pure PowerShell method is to check for running explorer.exe processes on the remote machine but that doesn't distinguish between active and disconnected sessions. That said, now may be the time to consider standardizing the installation language of your servers and having users make use of Set-WinUILanguageOverride for their personal UI language needs.

    – omniomi
    Mar 13 '17 at 13:30















    1














    Here's how I do it. It doesn't work for rdp sessions though.



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


    Or:



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





    share|improve this answer






























      1














      Here's how I do it. It doesn't work for rdp sessions though.



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


      Or:



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





      share|improve this answer




























        1












        1








        1







        Here's how I do it. It doesn't work for rdp sessions though.



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


        Or:



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





        share|improve this answer















        Here's how I do it. It doesn't work for rdp sessions though.



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


        Or:



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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 19 '17 at 13:40

























        answered Mar 15 '17 at 19:26









        js2010js2010

        1863




        1863























            -1














            this can be done with:




            get-wmiobject -Class Win32_Computersystem | select Username




            regards






            share|improve this answer
























            • It gives me empty result when I execute in remote machine from RDP :(

              – Reddy
              Mar 8 '17 at 15:51






            • 1





              the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

              – s0mm3r
              Mar 8 '17 at 16:04


















            -1














            this can be done with:




            get-wmiobject -Class Win32_Computersystem | select Username




            regards






            share|improve this answer
























            • It gives me empty result when I execute in remote machine from RDP :(

              – Reddy
              Mar 8 '17 at 15:51






            • 1





              the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

              – s0mm3r
              Mar 8 '17 at 16:04
















            -1












            -1








            -1







            this can be done with:




            get-wmiobject -Class Win32_Computersystem | select Username




            regards






            share|improve this answer













            this can be done with:




            get-wmiobject -Class Win32_Computersystem | select Username




            regards







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 8 '17 at 15:50









            s0mm3rs0mm3r

            1




            1













            • It gives me empty result when I execute in remote machine from RDP :(

              – Reddy
              Mar 8 '17 at 15:51






            • 1





              the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

              – s0mm3r
              Mar 8 '17 at 16:04





















            • It gives me empty result when I execute in remote machine from RDP :(

              – Reddy
              Mar 8 '17 at 15:51






            • 1





              the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

              – s0mm3r
              Mar 8 '17 at 16:04



















            It gives me empty result when I execute in remote machine from RDP :(

            – Reddy
            Mar 8 '17 at 15:51





            It gives me empty result when I execute in remote machine from RDP :(

            – Reddy
            Mar 8 '17 at 15:51




            1




            1





            the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

            – s0mm3r
            Mar 8 '17 at 16:04







            the wmi query only gets localy signed in users, to get rdp sessions try "qwinsta" here's a script i've got with one google search gallery.technet.microsoft.com/scriptcenter/…

            – s0mm3r
            Mar 8 '17 at 16:04




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Super User!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1186568%2fpowershell-get-active-logged-in-user-in-local-machine%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown