Easier way to parse 'query user' in PowerShell

Old question, but it seems a workable solution:

(query user) -split "\n" -replace '\s\s+', ';' | convertfrom-csv -Delimiter ';'

This chunks the output into lines, as the answer above does, but then replaces more than one white space character (\s\s+) with a semi-colon, and then converts that output from csv using the semi-colon as a delimiter.

The reason for more than one white space is that the column headers have spaces in them (idle time, logon time), so with just one space it would try to interpret that as multiple columns. From the output of the command, it looks as if they always preserve at least 2 spaces between items anyway, and the logon time column also has spaces in the field.


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


For gathering information.

based on https://ss64.com/nt/query-user.html

$result  = &quser
$result -replace '\s{2,}', ',' | ConvertFrom-Csv