отправить электронное письмо, если extensionAttribute равно

Я использую два отдельных сценария PowerShell. Первый вручную определяет дату для указанного пользователя extensionAttribute15. Второй, который мы намерены вызвать по расписанию, чтобы отправить электронное письмо через 14 дней после даты extensionAttribute15, но я получаю сообщение «Ошибка синтаксического анализа запроса». Он по-прежнему отправляет электронное письмо, но ссылка на дату не работает.

Первый сценарий:

          $username = Read-Host 'Enter username'
    $ADuser = Get-ADUser -Filter 'sAMAccountName -eq $username'
    $string = Read-Host = 'Please enter a date using the format MM/DD/YYYY'
    $Date= [DateTime] $string
    Write-Host $date -ForegroundColor DarkYellow
    set-aduser $username -replace @{extensionattribute15="$Date"}
    Get-ADUser -Identity $username    -Properties * | select extensionattribute15

Второй сценарий:

      import-module activedirectory
#Show me who
Get-ADUser -filter {extensionAttribute15 -eq (Get-Date).adddays(14) -and Description -like 'Test Do not modify' -and Enabled -eq $True} -Properties * | select CN, extensionAttribute15
$users = Get-ADUser -filter {extensionAttribute15 -eq (Get-Date).adddays(14) -and Description -like 'Test Do not modify' -and Enabled -eq $True} -Properties * | select CN, extensionAttribute15
$users | Foreach-Object{
    $message = (Get-Content "C:\Test\reminder.htm" | Out-String )
    $message = $message -replace "USRname",$_.GivenName
    $message = $message -replace "USRalias",$_.SamAccountName
    $message = $message -replace "USRemail",$_.EmailAddress
    
    ### SMTP Mail Settings
    $SMTPProperties = @{
        To = $_.EmailAddress
        From = "me@org.org"
        Subject = "Reminder: Action Required"
        SMTPServer = "mail.org.org"
    }
    Send-MailMessage @SMTPProperties -Body $message -BodyAsHtml
}

Как мне лучше всего определить атрибут extension как дату, а затем использовать его для вызова электронной почты в будущем?

Спасибо!

2 ответа

Вы можете форматировать даты так, как вам нравится, в extensionAttribute15, поэтому, если вы предпочитаете формат MM/dd/yyyy, тогда это нормально, если вы разбираете их точно таким же образом.

В сценарии 1 измените

      Set-ADUser $username -replace @{extensionattribute15="$Date"}

к

      # make sure the formatting is exactly how you want to parse it later
$dateToInsert = '{0:MM/dd/yyyy}' -f $Date
Set-ADUser $username -replace @{extensionattribute15=$dateToInsert}

Затем используйте сценарий 2, например:

      $refDate = (Get-Date).AddDays(14).Date   # 14 days from now
$message = Get-Content 'C:\Test\reminder.htm' -Raw
$filter  = "extensionAttribute15 -like '*' -and Description -like '*Test Do not modify*' -and Enabled -eq 'True'"
# or use -LDAPFilter "(&(extensionAttribute15=*)(description=*Test Do not modify*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"

Get-ADUser -Filter $filter -Properties extensionAttribute15, EmailAddress | 
    Where-Object { [datetime]::ParseExact($_.extensionAttribute15, 'MM/dd/yyyy', $null) -eq $refDate } | Foreach-Object {
    Write-Host "Sending email to user $($_.Name)"
    ### SMTP Mail Settings
    $SMTPProperties = @{
        To         = $_.EmailAddress
        From       = 'me@org.org'
        Subject    = 'Reminder: Action Required'
        SMTPServer = 'mail.org.org'
        # you can chain multiple -replace
        Body       = $message -replace 'USRname', $_.GivenName -replace 'USRalias', $_.SamAccountName -replace 'USRemail', $_.EmailAddress
        BodyAsHtml = $true
    }
    Send-MailMessage @SMTPProperties
}

$date = (Get-Date).date

$usersToActive =Get-ADUser -Filter "extensionAttribute15 -like '*'" -Properties extensionAttribute15 |where-object {[datetime]::Parse($_.extensionAttribute15).AddDays(-14) -eq $ date}

Ищу пользователей с чем-то в атрибуте, а затем через 14 дней в будущем.

через.

Другие вопросы по тегам