query user with powershell, output to email
I figured I would post my solution as I got it to format the way I wanted. Thank you Lee_Dailey. I'm sure there is a shorter route but I am new to this.
function Get-TSSessions {
param(
$ComputerName = "localhost"
)
query user /server:$ComputerName |
#Parse output
ForEach-Object {
# trim spaces at beginning and end
$_ = $_.trim()
# insert , at specific places for ConvertFrom-CSV command
$_ = $_.insert(22,",").insert(42,",").insert(47,",").insert(56,",").insert(68,",")
# Remove every space two or more spaces
$_ = $_ -replace "\s\s+",""
# for debug purposes, comment out above row and uncomment row below
#$_ = $_ -replace "\s","_"
# output to pipe
$_
} |
#Convert to objects
ConvertFrom-Csv
}
$users = foreach ($user in GET-TSSessions)
{
if ($user.'IDLE TIME' = ".") {
$idletime = "Not Idle"
} else {
$idletime = $user.'IDLE TIME'
}
"<table width='100%'>
<tr>
<td><b>Username:</b></td>
<td><b>Sesstion Type:</b></td>
<td><b>Session ID:</b></td>
<td><b>Sesstion State:</b></td>
<td><b>Idle Time:</b></td>
<td><b>Logon Time:</b></td>
</tr>
<tr>
<td>"+$user.USERNAME+"</td>
<td>"+$user.SESSIONNAME+"</td>
<td>"+$user.ID+"</td>
<td>"+$user.STATE+"</td>
<td>"+$idletime+"</td>
<td>"+$user.'LOGON TIME'+"</td>
</tr>
</table>"
}
$SmtpServer = '127.0.0.1' # SMTP Server name
$Port = 25 # SMTP server port number – default is 25
$From = '[email protected]' # from address - doesn't have to be valid, just in the format [email protected] and something your mail filter will not block
$To = '[email protected]' # email address to send test to
$Subject = 'Server login detected' # email subject
$Body = 'This is an automated alert to notify you that there has been a change in user status:<br /><br />
'+$users+'
' # email body
Send-MailMessage -SmtpServer $SmtpServer -Port $Port -From $From -To $To -Subject $Subject -BodyAsHtml $Body