Send-MailMessage, никогда не указывайте когда LastLogonDate = never? - PullRequest
0 голосов
/ 22 октября 2019

Используя приведенные ниже пс, я отправляю электронное письмо определенным свойствам учетной записи AD, включая LastLogonDate. Если учетная запись никогда не использовалась, электронная почта полностью пропускает значение. Я хотел бы, чтобы в сообщении содержалось что-то вроде следующего: Джон Смит входил в наши системы в общей сложности 0 раз с последним успешным входом в систему, опубликованным в N / A. Как я могу изменить то, что мне нужно для этого? Спасибо!

# List every active account with a "SACRequest Account" desctription that will expire in 0,7,14 days and inlcude the name and email address of the original account requester (extensionAttribute1,extensionAttribute2)
import-module activedirectory
$Today = Get-Date -Format 'MM-dd-yyy'
$Rightnow = Get-Date -Format o
$reportObject = @()
$userList = get-aduser -filter {Description -like "SACRequest Account" -and Enabled -eq $True} -Properties displayname, accountExpires, description, passwordexpired,"msDS-UserPasswordExpiryTimeComputed",enabled,AccountExpirationDate,LastLogonDate,logoncount,passwordlastset, badlogoncount,lastbadpasswordattempt,extensionAttribute1,extensionAttribute2,department | 
select displayname, accountExpires, description, passwordexpired,"msDS-UserPasswordExpiryTimeComputed",enabled,AccountExpirationDate,LastLogonDate,logoncount,passwordlastset, badlogoncount,lastbadpasswordattempt,extensionAttribute1,extensionAttribute2,department |
sort-object msDS-UserPasswordExpiryTimeComputed -descending
$obj = new-object PSobject
foreach ($user in $userList) 
{
$obj = new-object PSobject
    $obj | add-member noteproperty Name($user.displayname)
    $obj | add-member noteproperty Description($user.description)
    $obj | add-member noteproperty 'Password Expired'($user.Passwordexpired)
    $obj | add-member noteproperty 'Account is Enabled'($user.Enabled)
    $obj | add-member noteproperty 'AccountExpirationDate'($user.AccountExpirationDate.ToString('MM-dd-yyyy'))
    $obj | add-member noteproperty 'LastLogonDate'($user.LastLogonDate.ToString('MM-dd-yyyy'))
    $obj | add-member noteproperty 'Password Last Set'($user.PasswordLastSet)   
    $obj | add-member noteproperty 'Failed Logon Attempt'($user.lastbadpasswordattempt) 
    $obj | add-member noteproperty 'TotalLogonCount'($user.logoncount)
    $obj | add-member noteproperty 'Total Failed Logons'($user.badlogoncount)
    $obj | add-member noteproperty 'SACSubmitter'($user.extensionAttribute1)
    $obj | add-member noteproperty 'SACSubmitterEmail'($user.extensionAttribute2)
    $obj | add-member noteproperty 'Department'($user.department)
    $reportObject += $obj}

$from    =  "System Access Control <systems@organization.org>"

foreach ($user in $reportObject) {
  if (([datetime]$user.AccountExpirationDate).AddDays(-0) -eq $TodayOnly) 
  {
    $Name = $user.name
    $to = $user.SACSubmitterEmail
    $subject =  "Your contractors's login account will expire today!"
    $hello = $user.SACSubmitter
    $AccountExpirationDate = $user.AccountExpirationDate # -as [datetime]
    $TotalLogonCount = $user.TotalLogonCount
    $LastLogonDate = $user.LastLogonDate
    $body =  "Hello $hello,<br><br>"
    $body +=  "The login account you requested for <b>$Name</b> will expire in one week on <b> $AccountExpirationDate</b>.<br><br>"
    $body +=  "$name logged onto our systems a total of <b>$TotalLogonCount</b> times with the last successful log in posted on <b> $LastLogonDate</b>.<br><br>"
    $body +=  "<a href='http://intranet/form.cfm?id=100'>If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>"
    $body +=  "Kind Regards,<br>"
    $body +=  "Your friends in IT<br><br><br>"
    $body +=  "<i>Data generated $RightNow</i>"
    $mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
    $mail.IsBodyHTML=$true
    $server = "mail.organization.org"
    $port   = 25
    $Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
    $Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
    $smtp.send($mail)
}
}

foreach ($user in $reportObject) {
  if (([datetime]$user.AccountExpirationDate).AddDays(-7) -eq $TodayOnly) 
  {
    $Name = $user.name
    $to = $user.SACSubmitterEmail
    $subject =  "Your contractors's login account will expire in one week!"      
    $hello = $user.SACSubmitter
    $AccountExpirationDate = $user.AccountExpirationDate # -as [datetime]
    $TotalLogonCount = $user.TotalLogonCount
    $LastLogonDate = $user.LastLogonDate
    $body =  "Hello $hello,<br><br>"
    $body +=  "The login account you requested for <b>$Name</b> will expire in one week on <b> $AccountExpirationDate</b>.<br><br>"
    $body +=  "$name logged onto our systems a total of <b>$TotalLogonCount</b> times with the last successful log in posted on <b> $LastLogonDate</b>.<br><br>"
    $body +=  "<a href='http://intranet/form.cfm?id=100'>If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>"
    $body +=  "Kind Regards,<br>"
    $body +=  "Your friends in IT<br><br><br>"
    $body +=  "<i>Data generated $RightNow</i>"
    $mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
    $mail.IsBodyHTML=$true
    $server = "mail.organization.org"
    $port   = 25
    $Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
    $Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
    $smtp.send($mail)
}
}

foreach ($user in $reportObject) {
  if (([datetime]$user.AccountExpirationDate).AddDays(-14) -eq $TodayOnly) 
  {
    $Name = $user.name
    $to = $user.SACSubmitterEmail
    $subject =  "Your contractors's login account will expire in two weeks!"      
    $hello = $user.SACSubmitter
    $AccountExpirationDate = $user.AccountExpirationDate # -as [datetime]
    $TotalLogonCount = $user.TotalLogonCount
    $LastLogonDate = $user.LastLogonDate
    $body =  "Hello $hello,<br><br>"
    $body +=  "The login account you requested for <b>$Name</b> will expire in one week on <b> $AccountExpirationDate</b>.<br><br>"
    $body +=  "$name logged onto our systems a total of <b>$TotalLogonCount</b> times with the last successful log in posted on <b> $LastLogonDate</b>.<br><br>"
    $body +=  "<a href='http://intranet/form.cfm?id=100'>If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>"
    $body +=  "Kind Regards,<br>"
    $body +=  "Your friends in IT<br><br><br>"
    $body +=  "<i>Data generated $RightNow</i>"
    $mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
    $mail.IsBodyHTML=$true
    $server = "mail.organization.org"
    $port   = 25
    $Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
    $Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
    $smtp.send($mail)
}
}

Ответы [ 2 ]

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

1.) Удалите этот первый объект PSob, он не нужен. замените на шаг 2

  $obj = new-object PSobject
  foreach ($user in $userList) 
  {

2.) выделите 0-дневных пользователей из списка пользователей

$0dayUsers = $userList  |Where-Object {$_.LastLogonDate -like ''}

3.) удалите 0-дневных пользователей из исходного списка

$userList = $userList  |Where-Object {$_.LastLogonDate -notlike ''}

3.) Добавьте это под своим 14-дневным уведомлением подрядчика внизу, добавив одно изменение. Я оставил вам вопрос о том, как адаптировать образец для вашей целевой аудитории

foreach ($user in $0dayUsers) {


    $Name = $user.name
    $to = $user.SACSubmitterEmail

    $subject =  "Notice regarding orphaned account!" 

    $hello = $user.SACSubmitter
    $AccountExpirationDate = $user.AccountExpirationDate # -as [datetime]
    $TotalLogonCount = $user.TotalLogonCount
    $LastLogonDate = $user.LastLogonDate
    $body =  "Hello $hello,<br><br>"
    $body +=  "The login account you requested for <b>$Name</b> will expire in one week on <b> $AccountExpirationDate</b>.<br><br>"
    $body +=  "$name logged onto our systems a total of <b>$TotalLogonCount</b> times with the last successful log in posted on <b> </b>.<br><br>"
    $body +=  "<a href='http://intranet/form.cfm?id=100'>If this account needs to remain active please submit a new System Access Control Request by clicking here.</a><br><br>"
    $body +=  "Kind Regards,<br>"
    $body +=  "Your friends in IT<br><br><br>"
    $body +=  "<i>Data generated $RightNow</i>"
    $mail = New-Object System.Net.Mail.Mailmessage $from, $to, $subject, $body
    $mail.IsBodyHTML=$true
    $server = "mail.organization.org"
    $port   = 25
    $Smtp = New-Object System.Net.Mail.SMTPClient $server,$port
    $Smtp.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
    $smtp.send($mail)
}

### The single curly brace is intentional, the if statement was removed since Select-Object already handled it.

5.) hope that helps :) 
0 голосов
/ 22 октября 2019

Вы ищете что-то вроде

if ($user.LastLogonDate){
   #$user.LastLogonDate is not null, use the value
   $obj | add-member noteproperty 'LastLogonDate'($user.LastLogonDate.ToString('MM-dd-yyyy'))
} else {
    #$user.LastLogonDate is null, use never
   $obj | add-member noteproperty 'LastLogonDate' 'Never'
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...