
Just recently I have been developing a Powershell script to determine if a specific user on a Windows Terminal Server is logged in or not. If the user happens to not be logged in, It will e-mail a message to me and another co-worker to log that user in immediately.
It basically uses the quser command to get a list of the currently logged in users on the terminal server and stores that info into the variable $nwt. I then setup a if statement to see if it matches “nwt” which is the username I want to make sure is logged in at all times. If it does not find the string nwt in the $nwt variable, it will then send an e-mail to myself and a co-worker notifying us that he is not logged in. This is possible via the “System.Net.Mail” .net object in the .net framework. Here is a site with more information on the System.Net.Mail object, that helped me add a CC address to the e-mail, here is the link: systemnetmail.com. And that’s really all there is too it!
So far the script has been a success, since it has alerted us as to when this critical user account logs out so we can quickly log him back in. (We have some software that needs this specific user account to run properly.. it’s really crappy software..)
Below is the code:
——————————————————————-
$nwt = invoke-expression -Command "quser nwt"
$date = date
if($nwt -is [Array]){
if($nwt[1] -match "nwt"){
write-host "--> NWT is logged in!"
echo "--> NWT is logged in! [ $date ]" > ./nwt.log
}
}else{
write-host "--> [ Problem ] NWT is not logged in!"
$emailFrom = "administrator@example.com"
$emailTo = "youremail@example.com"
$subject = "NWT is not logged in"
$body = "
The NWT user account is not logged in on Termserver. This was detected at:[ $date ]"$smtpServer = "mail.example.local"
$msg = new-object System.Net.Mail.MailMessage $emailFrom, $emailTo,
$subject, $body
$msg.CC.Add("co-worker@example.com")
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($msg)
}
——————————————————————-



