Email logon alert windows server

Greetings, I’m working on a powershell code that alerts you by email when a user is right on the server.
When the login is local on the machine itself the alert is sent correctly, but when directly via terminal server, the email does not show the username of the logged in user.
How do I fix this error? Here’s a copy of the code below:


Function Send-Mail {

$User = (Get-WmiObject -Class win32_computersystem -ComputerName .).UserName
$strHost = [Environment]::MachineName

$Content = “

Alerta de email

” +
“<br>” +
“<font size=‘4’>” +
“The user ” + $User + “ logged in to the server: ” + $strHost + “” +
“<br>” +
“Schedule: ” + (Get-Date).toString(“dd/MM/yyyy HH:MM:ss”) + “</font>”

$Assunto = "The user " + $User + " logged in to server: " + $strHost

$strDe = “”
$strPara = “”
$strPwd = “xyxyxyxyxy”
$strConteudo = $Content
$SMTPServer = “”
$SMTPMessage = New-Object System.Net.Mail.MailMessage($strDe,$strPara,$Assunto,$strConteudo)
$SMTPMessage.IsBodyHtml = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($strDe, $strPwd);
Remove-Variable -Name SMTPClient
Remove-Variable -Name strPwd


[/ pre]

its difficult to understand the code(formatting), can you post it in and share the link here ?


Can you clarify if you are running this code remotely or locally on the computer? If I understand correctly you are looking to pull the users from a remote server as well?