Если срок действия учетной записи составляет менее 30 дней, отправьте письмо их менеджеру - PullRequest
0 голосов
/ 07 октября 2019

Сценарий: если учетная запись включена и срок ее действия составляет менее 30 дней, отправьте электронное письмо их менеджеру.

Проблема: мой сценарий powershell отправляет электронное письмо менеджеру учетных записей как при включении, так и при отключении пользователя. Я пытался что-то изменить в IF IF, потому что я чувствую, что что-то там не так, но все еще не могу решить проблему. Кто-нибудь знает, как / где я должен изменить в этом сценарии?

import-module ActiveDirectory;

Get-ADUser -Filter * -SearchBase 'OU=Product Owners,OU=Employees,OU=Cloud Users,DC=0000,DC=0000' -Properties directReports, EmailAddress, Displayname | ForEach {
	$ManagerName = $_.Displayname
Write-Host $_.directReports
$Body = "
                        <html>
                        <body> 
                        <p style='font-size:12.0pt;font-family:Arial'>Hej $ManagerName,<br/><br>
                        Du har f&aring;tt detta mail f&ouml;r att du &auml;r ansvarig f&ouml;r de personer som listas nedan. De har &aring;tkomst till sina rika PIM-klienter via VPN.<br><br>
                        <style>
                        TABLE {font-family:Arial; border-width: 0px; border-style: solid; border-color: black; border-collapse: collapse; border-spacing: 0;}
                        TH {border-width: 1px; padding: 7px; border-style: solid; border-color: black; background-color: #2079B5; color: white;}
                        TD {border-width: 1px; padding: 7px; border-style: solid; border-color: black;}
                        </style>
                        <table>
                        <tbody>
                        <tr><th>Namn</th><th>E-postadress</th><th>Kontots utg&aring;ngsdatum</th></tr>";
$AddBody = "";

If ($_.directReports)
{
	
	Write-Output("Processing : " + $ManagerName);
	$ToEmail = $_.EmailAddress
	
	$_.directReports | ForEach {
		
		$userDetails = Get-ADUser $_ -Properties AccountExpirationDate, accountExpires, EmailAddress, Enabled
		
		$userName = $userdetails.Name
		$userEmail = $userdetails.EmailAddress
		Write-Host $userDetails.accountExpires

		If ($userDetails.accountExpires -eq 0 -or $userDetails.accountExpires -eq 9223372036854775807 -or $userDetails.Enabled -eq $false)
		{
			
			$sendEmail = $false
		}
		
		If ($userDetails.AccountExpirationDate -and $userDetails.Enabled -eq $true -and $userDetails.accountExpires -ne 0)
		{
			
			$ExpiryDate = $userDetails.AccountExpirationDate
			
			$ExpiryDate1 = $ExpiryDate.ToShortDateString()
			
			$today = (Get-Date)
			
			$DaysLeft = ($ExpiryDate - $today).days
			
			If ($DaysLeft -le 30 -and $DaysLeft -ge 0)
			{
				$AddBody += "<tr><td>$userName</td> <td><a style='text-decoration:none;color: rgb(0, 0, 0);'>$userEmail</a></td> <td>$ExpiryDate1</td> </tr>";
				$sendEmail = $true
			}
			
		}
	}
	
	If ($sendEmail)
	{
		Write-Output("Sending mail to : " + $ManagerName);
        
		$Body += $AddBody;
		$Body = $Body + "</tbody>
                            </table><br>

                            <p style='font-size:12.0pt;font-family:Arial'>V&auml;nligen meddela oss p&aring; ISS s&aring; snart som m&ouml;jligt genom att svara p&aring; detta mail. Ange om kontona ska f&ouml;rl&auml;ngas 6 m&aring;nader eller avslutas. <br>
							Har du n&aring;gra fr&aring;gor, tveka inte att kontakta oss. <br><br>
							<font color=104160 size=5></font></p>
                            <p style='font-size:12.0pt;font-family:Arial'>Med v&auml;nlig h&auml;lsning<br />
                            ISS
                            </span></b><span style='font-size:12.0pt;font-family:Arial;
                            color: black'><o:p></o:p></span><br />
							<a href='mailto:support.cloud@fiwe.se'><span style='font-size:12.0pt'>support.cloud@fiwe.se</span></a><br><br>
							<img src='http://fiwe.com/signature/v2/img/footer_new.jpg'><br>
							<p style='font-size:6.0pt;font-family:Arial'>Important Note: This e-mail and any attachment thereof are confidential and may contain trade secrets and may also be legally privileged otherwise protected from disclosure. If you have received <br>
							it in error, you are in notice of its status. Please notify us immediately by reply e-mail and then delete this e-mail and any attachment from your system. If you are not the intended recipient please
							<br>understand that you must not copy thise-mail or any attachment or disclose the contents to any other person.
                            
                            
                            </body>  
                            </html>";
			Write-Output($Body);
			$Body > 'file.html'
			send-mailmessage -To $ToEmail -From support.cloud@fiwe.se -Encoding UTF8 -Subject "Användarkonton Fiwe cloud på väg att gå ut, åtgärd krävs." -body $Body -smtpserver 10.122.25.7 -BodyAsHtml -Priority High
		
	}
else{
	"No accounts about to expire." > 'log.csv'
	
	}	
}
}

1 Ответ

0 голосов
/ 07 октября 2019

Проблема вызвана установкой и сбросом sendEmail в цикле foreach.

$_.directReports | ForEach {
    ...
    If ($userDetails.accountExpires -eq 0 -or $userDetails.accountExpires -eq 9223372036854775807 -or $userDetails.Enabled -eq $false) {
        $sendEmail = $false
    }

    If ($userDetails.AccountExpirationDate -and $userDetails.Enabled -eq $true -and $userDetails.accountExpires -ne 0){
        ...
            $sendEmail = $true
    }
}

If ($sendEmail) {

Поскольку переменная обновляется несколько раз, окончательное значение устанавливается последней итерацией. Неважно, какие значения были установлены на более ранних итерациях, учитывается только последняя.

Чтобы это исправить, может быть, что-то похожее

$AddBody = [string]::Empty # or $AddBody = ""
...
if $AddBody.Length -gt 1 {
    #send email, as $AddBody would contain expiry info
}

будет работать лучше. (Еще во времена .Net 1, "" и String :: Empty были разные вещи .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...