我在power-shell中有一个脚本,可以从多个服务器注销断开连接的会话,每当它从各个服务器注销断开连接的用户时,它就会向我发送一封电子邮件。截至目前,当脚本从多个服务器注销用户时,我收到多封电子邮件。我正在尝试添加功能,它列出了从脚本中注销的用户,并仅向我发送一封包含用户列表的电子邮件。脚本如下: -
$servers = get-content “C:\Users\Desktop\server.txt”
foreach($Server in $Servers) {
try {
$disconnectedusers = @()
query user /server:$Server 2>&1 | select -skip 1 | ? {($_ -split "\s+")[-5] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-6] /server:$Server /V ; $disconnectedusers += ($_ -split "\s+")[1]}
If($disconnectedusers -ge 1)
{
Send-MailMessage -to xx@xx.com -from sc@sc.com -Subject "List of Disconnected Users Logged Off" -Body "Disconnected User session for user:-$disconnectedusers on server $Server has been Logged off." -SmtpServer smtp.gmail.com
}
}
catch {}
}
非常感谢任何帮助。
答案 0 :(得分:0)
这是一个修改后的版本,我感谢你,我将安排今晚的任务。我将电子邮件转换为HTML,因此它比您想要的更多,但我认为您会得到这个想法。
主要的是在foreach循环外部创建数组以及发送if语句的电子邮件,否则它将在循环中处理每个服务器。
$servers = get-content “C:\Users\Desktop\server.txt”
$disconnectedusers = $null
$disconnectedusers = @()
$failed = @()
$style = "<style>
body {
font-family: calibri;
font-size: 12px;
color: #000;
}
h1 {
font-size: 16px;
margin-bottom: 10px;
}
table {
border: solid 1px #ddd;
border-collapse: collapse;
width: 80%;
}
th{
background-color: #ddd;
font-weight: bold;
text-align: left;
padding: 5px;
}
td {
width: auto;
padding: 3px 20px 3px 5px;
text-align: left;
border-bottom: #ddd solid 1px;
}
</style>"
foreach($Server in $Servers) {
try {
query user /server:$Server 2>&1 | select -skip 1 | ? {($_ -split "\s+")[-5] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-6] /server:$Server /V; $disconnectedusers += New-Object PSObject -Property @{"Server" = $Server; "SamAccountName" = $(($_ -split "\s+")[1])}}
}
catch [Exception] {
$failed += $($Server + ": " + $_.Exception.Message)
}
}
If($disconnectedusers) {
Send-MailMessage -to xx@xx.com -from noreply@xx.com -Subject "List of Disconnected Users Logged Off" `
-Body $($style + "<h1>Disconnected User sessions</h1><p>All sessions in the below table have been logged off.</p>"+ $($disconnectedusers | ConvertTo-Html -Fragment)) `
-SmtpServer "smtp.gmail.com" -BodyAsHtml -Priority "High"
}