我不知道我在 powershell 中哪里做错了。我试图在用户更改时向自己登录的用户帐户发送电子邮件,但我无法让它正常工作,它只会给我乱码的未格式化的消息。它在一定程度上有效,但我希望它被格式化,而不是通过电子邮件向我发送一行。
这可能吗?
$users = query user /server:localhost
$SmtpServer = 'xx.xx.xx.xx' # 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 = 'xxx.xx.xx.xx - Server login detected of account.' # email subject
$Body = 'This is an automated alert to notify you that there has been a change in user status:
'+$users+'
' # email body
Send-MailMessage -SmtpServer $SmtpServer -Port $Port -From $From -To $To -Subject $Subject -Body $Body ```
I get the email as follows:
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME accountname rdp-tcp#39 3 Active . 3/30/2021 5:54 PM accountname2 rdp-tcp#94 9 Active 29 3/30/2021 9:01 PM
答案1
我想我会发布我的解决方案,因为我已经将它格式化为我想要的方式。谢谢 Lee_Dailey。我确信有一条更短的路线,但我对此很陌生。
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