1
$dat = query user /server:$SERVER

this query gives below data

USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>vm82958               console             1  Active       1:28  2/9/2018    9:18 AM
adminhmc                                  2  Disc         1:28  2/13/2018 10:25 AM
nn82543                                   3  Disc         2:50  2/13/2018 3:07 PM    

I would like to get each independent user details like STATE, USERNAME, ID details. I tried below code but it is not giving any data

foreach($proc in $dat) {
    $proc.STATE  # This is not working  this command not giving any data.
    $proc.ID # This is not working  this command not giving any data.
}

Please help me on this.

The result of $dat.GetType() is:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
G42
  • 9,791
  • 2
  • 19
  • 34
surendra
  • 551
  • 3
  • 13
  • 27
  • Looks like you're trying to treat a String as an Object. What is the result of `$dat.GetType()`? – G42 Feb 13 '18 at 12:45
  • IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object it is giving as string. Then how can I get the details. – surendra Feb 13 '18 at 12:53
  • I have worked with this type of stuff before. https://stackoverflow.com/questions/29550324/how-can-i-output-all-the-output-of-a-called-command-in-powershell-script/29551078#29551078 would be a good candidate. Also here is a script that is used for parsing fixed width data https://stackoverflow.com/a/29130697/3829407 – Matt Feb 13 '18 at 13:27
  • Identical question with answer by Ansgar Wiechers: [Query user /server:server (filter content)](//stackoverflow.com/q/34745112) – henrycarteruk Feb 13 '18 at 14:23

2 Answers2

0

This is very similar to this StackOverflow post, but you have blank fields in your data.

One solution is to deal with this first. Example below but this may break given data that is very different to your example. For a more robust and complete solution see Matt's comment

# replace 20 spaces or more with TWO commas, because it signifies a missing field
$dat2 = $dat.Trim() -replace '\s{20,}', ',,'

# replace 2 spaces or more with a single comma
$datTable = $dat2.Trim() -replace '\s{2,}', ',,'

foreach($proc in $datTable) {
    $proc.STATE
    $proc.ID
}
G42
  • 9,791
  • 2
  • 19
  • 34
0

Another option is to use fixed Columns with string.Insert , like this:

$content = quser /server:$SERVER    
$columns = 14,42,46,54,65 | Sort -Descending
$Delimiter = ','

$dat = $content | % {
  $line = $_
  $columns | % {
    $line = $line.Insert($_, $Delimiter)
  }
  $line -replace '\s'
} |
ConvertFrom-Csv -Delimiter $Delimiter 

And Then:

foreach($proc in $dat) {
    $proc.STATE          
    $proc.ID # Will show the relevant Data
}
Avshalom
  • 8,657
  • 1
  • 25
  • 43