title: Return UserName and ServerName using Get-TSSession
body: <p>I'm writing a PS script that will search a textfile of terminal servers, find disconnected sessions and return the username and server name.</p>
  
  <p>The purpose is to send an email to users with disconnected sessions on a regular basis to try to get them to log off properly. When they don't log off they tend to keep our legacy data entry systems open which increases the incidence of index / table corruption.</p>
  
  <p>The code I have so far is thus:</p>
  
  <pre><code>$tsservers = Get-Content .\powershell\terminalservers.txt
  
  foreach ($i in $tsservers){
  
      #write-output $i
  
      $Sessions = Get-TSSession -ComputerName $i | where {(($_.state -eq "Disconnected"))} | Select -ExpandProperty UserName
      foreach ($session in $Sessions) {
  
          $query = "SELECT * from ds_user where ds_sAMAccountName='$session'"
          $user = Get-WmiObject -Query $query -Namespace "root\Directory\LDAP"
          $user.DS_mail
      }
  }
  </code></pre>
  
  <p>Using this I can retrieve their UserName and query AD to produce their email. I've tried many many times to work the server property into that code but to no avail.</p>
  
  <p>Edit 1: Ideally I would like to pass in multiple properties (eg: disconnect time, etc).</p>