下面的代码更改UPN后缀并记录它们。如果后缀发生了变化,如何让PowerShell通过电子邮件向我发送日志文件 ?
$domain = ([adsi]'').distinguishedName
$OU = "OU=TestUPNusers,OU=_TEST_OU_,$domain"
$suffix = '@test.UofGuelph.com'
$newsuffix = "@UofGuelph.com"
$CurrentUser= [Environment]::UserName
Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $OU |
foreach-object {
$upn = $_.userprincipalname.replace("$suffix","$newsuffix")
logwrite "changed the UPN suffix for : $UPN on $date"
set-aduser $_ -userprincipalname $upn
}
Function LogWrite{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
}
$logfile = "c:\logs\" + $currentuser + ".log”
$date = "{0:yyyy/MM/dd hh:mm}" -f (get-date)
logwrite "========================================="
logwrite "Script ran by $CurrentUser on $date"
logwrite "==============================
答案 0 :(得分:0)
如果Get-ADUser
返回任何结果,请使用Send-MailMessage(或类似函数)。例:
$users = @(Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $OU)
$users | foreach-object {
$upn = $_.userprincipalname.replace("$suffix","$newsuffix")
logwrite “changed the UPN suffix for : $UPN on $date"
set-aduser $_ -userprincipalname $upn
}
if($users.Count -gt 0) {
send-mailmessage -to "User01 <user01@example.com>" -from "User02 <user02@example.com>" -subject "Users has been changed" -Attachments "c:\logs\$($currentuser).log”
}
答案 1 :(得分:0)
您可以做的一件事是在脚本运行期间将日志数据转储到变量中。然后在最后检查日志变量中是否有东西。如果是,请写入日志文件,然后通过电子邮件发送:
Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $OU |
foreach-object {
$upn = $_.userprincipalname.replace("$suffix","$newsuffix")
$logfile += “changed the UPN suffix for : $UPN on $date`n"
set-aduser $_ -userprincipalname $upn
}
if($logfile)
{
$logfile | out-file <filename>
send-mailmessage -to user@dmain.com -from person@domain.com -subject $subject -body $logfile
}