title: Objectify the results of Qwinsta
body: <p>I am trying to write a script that will give me back as an object the results from qwinsta.
  The code of my script is this:</p>
  <pre><code>function Get-QWinsta {
      $queryResults = (qwinsta /Server:$ENV:COMPUTERNAME | ForEach-Object { ( ( $_.Trim() -replace &quot;\s+&quot;,&quot;,&quot;) ) } | ConvertFrom-Csv)
  
      $queryResults | ForEach-Object { if ( $_.SESSIONNAME -match 'da-' ) { 
                                          $_.USERNAME = $_.SESSIONNAME; $_.SESSIONNAME = $null; $_.STATE = $_.ID; $_.ID = $null 
                                          }
                                      
      }
      
      $RDPSESSIONS = $queryResults | ForEach-Object {
          [PSCustomObject]@{
              UserName = if ( $_.USERNAME -match '\d' ) { $_.USERNAME = $null } else { $_.USERNAME }
              SessionName = if ( $_.SESSIONNAME -match 'services|console' ) { $_.SESSIONNAME = $null } else { $_.SESSIONNAME } 
              SessionID = $_.ID
              SessionState = if ( $_.ID -match 'Disc' ) { $_.STATE = 'Disconnected' } else { $_.STATE }
          }
      } 
      return $RDPSESSIONS 
  }
  
  </code></pre>
  <p>and the output is this:</p>
  <pre><code>UserName    SessionName    SessionID    SessionState
  --------    -----------    ---------    ------------                                
                             Disc 
                             Conn
  Admin01                                 Disc                                        
  Admin02     rdp-tcp#41     4            Active
              rdp-tcp                     Listen
  </code></pre>
  <p>However the above is not a real object and what I would really want to have as output is something like this:</p>
  <pre><code>UserName     SessionName     SessionID     SessionState                                
  --------     -----------     ---------     ------------                                
  Admin01                                    Disc
  Admin02      rdp-tcp#41      4             Active
  </code></pre>
  <p>Plus if I could something like this:</p>
  <pre><code>&gt; $user1 = (Get-Qwinsta).UserName
  &gt; Write-Output $user1
  &gt; Admin01
  </code></pre>
  <p>that would be a bonus.</p>
  <p>I have read all the similar post here and everywhere on the internet and none of them worked perfectly fine or did what I want to achieve.</p>