not able to get into else if statement in powershell - powershell

I am having one source file(CertExpiry.csv) in csv format below:
CertName,Expiry,AlertEmail,UserName,WhereUsed,Type,Additional Info
something.test1.com,11/21/2021,tom#xyz.com,Tom,Test-WEU-APPGW,Internal CA,
something.test2.com,7/15/2021,"harry#xyz.com,tom#xyz.com",Harry,Test-SEA-APPGW,Internal CA,
something.test3.com,7/16/2021,"tom#xyz.com,harry#xyz.com",Tom,Test-EUS-APPGW,External CA,
something.test4.com,not set,"tom#xyz.com,harry#xyz.com",Tom,Test-EUS-APPGW,External CA,
and I have written below script to print some data based on matching condition but unfortunately I am not able to enter into else condition and its not printing data as per my wish.
$data=import-csv .\CertExpiry.csv
$days = "-30"
foreach($i in $data) {
$CertName = $i.CertName
$Expiry = $i.Expiry
$AlertEmail = $i.AlertEmail
$UserName = $i.UserName
$WhereUsed = $i.WhereUsed
$Type = $i.Type
write-host "$CertName - $Expiry" -foregroundcolor magenta
if($Expiry -eq "not set"){
write-host "Cert expiration date is not set for $CertName" -foregroundcolor Green
}
else {
$Expiry = get-date $Expiry
$Expiry1 = ($Expiry).adddays($days)
if($Expiry1 -le $date){
write-host "Cert $CertName will expire on $Expiry and alert email is $AlertEmail with $UserName and $WhereUsed and $Type" -foregroundcolor red
}
}
}

Abraham already pointed out where the error was ($date was never defined). I also added some improvements, the Limit Date should be defined outside the loop:
$csv = #'
CertName,Expiry,AlertEmail,UserName,WhereUsed,Type,Additional Info
something.test1.com,11/21/2021,tom#xyz.com,Tom,Test-WEU-APPGW,Internal CA,
something.test2.com,7/15/2021,"harry#xyz.com,tom#xyz.com",Harry,Test-SEA-APPGW,Internal CA,
something.test3.com,7/16/2021,"tom#xyz.com,harry#xyz.com",Tom,Test-EUS-APPGW,External CA,
something.test4.com,not set,"tom#xyz.com,harry#xyz.com",Tom,Test-EUS-APPGW,External CA,
something.test5.com,6/16/2021,"tom#xyz.com,harry#xyz.com",Tom,Test-EUS-APPGW,External CA,
'# | ConvertFrom-Csv
$limitDate = (Get-Date).AddDays(-30)
foreach($i in $csv)
{
$CertName = $i.CertName
$Expiry = $i.Expiry -as [datetime]
$AlertEmail = $i.AlertEmail
$UserName = $i.UserName
$WhereUsed = $i.WhereUsed
$Type = $i.Type
if(-not $Expiry)
{
Write-host "Cert expiration date is not set for $CertName" -ForegroundColor Green
continue
}
if($Expiry -le $limitDate)
{
Write-Host "Cert $CertName will expire on $Expiry and alert email is $AlertEmail with $UserName and $WhereUsed and $Type" -ForegroundColor Red
continue
}
Write-Host "$CertName - $Expiry" -ForegroundColor Magenta
}
This results in:
something.test1.com - 11/21/2021 00:00:00
something.test2.com - 07/15/2021 00:00:00
something.test3.com - 07/16/2021 00:00:00
Cert expiration date is not set for something.test4.com
Cert something.test5.com will expire on 06/16/2021 00:00:00 and alert email is tom#xyz.com,harry#xyz.com with Tom and Test-EUS-APPGW and External CA

Related

Extending Bulk AD Accounts Expiration date by 6 months via PowerShell

I am fairly new to PowerShell and this maybe straight forward for a professional.
I am looking to extend expiration date a bulk of AD usernames in a text file by 6 months.
Preferably if the code could pick up the current date and extend from there.
As I have been doing some googling and testing I am come up with the command to do a single account in PowerShell:
Set-ADAccountExpiration SMahmood -DateTime "06/11/2022"
The above command I obviously have to change the username and date (if I run the command on different day) every time I run the command.
I have also managed to find some script of another person who asked a similar question but his script asks you to define the username each time you would like to extend it (this is not my code but has been tested as working) :
$continue = $true
while ($continue) {
write-host " AD Account Expiration Date Changer" -ForegroundColor White
Write-Host ""
while ($true) {
try {
# Loop until a valid username is entered
$Entered_Username_0 = Read-Host "Enter a username"
$Entered_Username = $Entered_Username_0.Trim()
if (Get-ADUser -Identity $Entered_Username | Out-Null) {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Invalid username entered!" -ForegroundColor Red
Write-Host ""
}
}
$dateMin = [datetime]::Now
$dateMin_short = $dateMin.ToShortDateString()
Write-Host "Press 1 to extend the account expiration date by 6 months"
Write-Host "Press 2 to extend the account expiration date to a sprecific date"
$Choice_input = Read-Host "Please select an option"
while ($true) {
try {
if ($Choice_input -eq 2) {
while ($true) {
try {
# Loop until a valid Date is entered and that Date is above $dateMin
$Entered_Date = [datetime]::ParseExact(
(Read-Host "Enter a new expiry date, in the format DD/MM/YYYY"),
'dd/MM/yyyy',
[System.Globalization.CultureInfo]::new('en-GB')
)
if ($Entered_Date -lt $dateMin) {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Invalid date entered! Format must be DD/MM/YYYY and higher than $dateMin_short." -ForegroundColor Red
Write-Host ""
}
}
}
if ($Choice_input -eq 1) {
$Entered_Date = [datetime]::Now.addmonths(6)
}
else {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Please input a either 1 or 2." -ForegroundColor Red
Write-Host ""
}
}
try {
Set-ADAccountExpiration -Identity $Entered_Username -DateTime $Entered_Date.AddHours(24)
Write-Host ""
Write-Host "New account expiration date for $Entered_Username is $(($Entered_Date).toString('dd/MM/yyyy'))"-ForegroundColor Green
$Entered_Date = ($Entered_date).toString('dd/MM/yyyy')
}
catch {
Write-Host ""
Write-Host "Unable to set account expiry: $_"-ForegroundColor Red
}
Write-Host ""
}
$continue = $true
while ($continue) {
write-host " AD Account Expiration Date Changer" -ForegroundColor White
Write-Host ""
while ($true) {
try {
# Loop until a valid username is entered
$Entered_Username_0 = Read-Host "Enter a username"
$Entered_Username = $Entered_Username_0.Trim()
if (Get-ADUser -Identity $Entered_Username | Out-Null) {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Invalid username entered!" -ForegroundColor Red
Write-Host ""
}
}
$dateMin = [datetime]::Now
$dateMin_short = $dateMin.ToShortDateString()
Write-Host "Press 1 to extend the account expiration date by 6 months"
Write-Host "Press 2 to extend the account expiration date to a sprecific date"
$Choice_input = Read-Host "Please select an option"
while ($true) {
try {
if ($Choice_input -eq 2) {
while ($true) {
try {
# Loop until a valid Date is entered and that Date is above $dateMin
$Entered_Date = [datetime]::ParseExact(
(Read-Host "Enter a new expiry date, in the format DD/MM/YYYY"),
'dd/MM/yyyy',
[System.Globalization.CultureInfo]::new('en-GB')
)
if ($Entered_Date -lt $dateMin) {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Invalid date entered! Format must be DD/MM/YYYY and higher than $dateMin_short." -ForegroundColor Red
Write-Host ""
}
}
}
if ($Choice_input -eq 1) {
$Entered_Date = [datetime]::Now.addmonths(6)
}
else {
throw
}
break
}
catch {
Write-Host ""
Write-Host "Please input a either 1 or 2." -ForegroundColor Red
Write-Host ""
}
}
try {
Set-ADAccountExpiration -Identity $Entered_Username -DateTime $Entered_Date.AddHours(24)
Write-Host ""
Write-Host "New account expiration date for $Entered_Username is $(($Entered_Date).toString('dd/MM/yyyy'))"-ForegroundColor Green
$Entered_Date = ($Entered_date).toString('dd/MM/yyyy')
}
catch {
Write-Host ""
Write-Host "Unable to set account expiry: $_"-ForegroundColor Red
}
Write-Host ""
}
Big thanks Vihaan Reyansh who provided the script above I had to tweak it a bit as it was changing the description field.

Setting variables based on value taken from CSV within a Foreach loop using an if else statement

I've created a script that takes new user data from a CSV file and connects to AzureAd and ExchangeOnline to create their AzureAD account, assigns them an Office license (not shown), and updates their Mailbox Office field.
CSV headers are Name, Department, OfficeLocation. The CSV used to contain a Domain and Company header. I removed those headers and added an if elseif statement to provide the logic to set those variables within the script. Prior to this addition, the script worked without any issues.
Now, the $company and $domain values are only updating for $main_offices and $corporate_offices Contoso and #contoso.com even when the OfficeLocation value is San Francisco or Austin and those values should be West/South Acme and west/south.acme.com.
Why are my $company and $domain values not being updated within the ForEach-Object loop as it iterates through the CSV? I confirmed that $company and $domain update properly when not reading in CSV data with ForEach-Object:
$new_users = Import-Csv -Path .\new-users.csv
...
$main_offices = 'New York','Los Angeles','Houston','Atlanta','Chicago'
$corporate_offices = 'Corporate Office (NY)','Corporate Office (LA)'
$west_office = 'San Francisco'
$south_office = 'Austin'
$new_users | ForEach-Object {
$first, $last = $_.Name.Split()
$mailnickname = $(($first.Substring(0,1) + $last).ToLower())
$password_profile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$password_profile.Password = 'XXXXXXXXXXXXXXXXXX'
$password_profile.ForceChangePasswordNextLogin = $false
$off_loc = $_.OfficeLocation
if ($off_loc -in $main_offices -or $corporate_offices) {
$company = 'Contoso'
$domain = '#contoso.com'
} elseif ($off_loc -eq $west_office) {
$company = 'West Acme'
$domain = '#west.acme.com'
} elseif ($off_loc -eq $south_office) {
$company = 'South Acme'
$domain = '#south.acme.com'
} else { $off_loc = Read-Host 'Type an office location' } #CSV OfficeLocation field either missing or has a spelling error
$attr_new_user = #{
AccountEnabled = $true
CompanyName = $company
Department = $_.Department
DisplayName = $_.Name
GivenName = $first
MailNickname = $mailnickname
PasswordProfile = $password_profile
Surname = $last
UsageLocation = 'US'
UserPrincipalName = $mailnickname + $domain
}
try {
Write-Host ('>> Creating account for ' + $attr_new_user.DisplayName) -ForegroundColor Yellow
New-AzureADUser #attr_new_user | Out-Null
$user_upn = Get-AzureADUser -ObjectId $attr_new_user.UserPrincipalName | Select-Object -ExpandProperty UserPrincipalName
Write-Host ('>> ' + $user_upn + ' has been created') -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
...
try {
Write-Host ('>> Adding email alias: ' + $alternate_email + ' and office: ' + $off_loc + ' to ' + $user_upn) -ForegroundColor Yellow
Set-Mailbox -Identity $user_upn -EmailAddresses #{ add = $alternate_email } -Office $off_loc
Write-Host ('>> Email Alias: ' + $alternate_email + ' and office: ' + $off_loc + ' added to ' + $user_upn) -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
I've run the script and the $off_loc value is being inputted correctly in the Office field of the Mailbox settings. Which is why I am having trouble understanding how to get this information to create the user with the correct the $company and $domain fields.
Any insight into a solution to this issue is appreciated, thank you for taking the time to answer my question.
Per Santiago Squarzon:
This condition $off_loc -in $main_offices -or $corporate_offices will
always be $true because $corporate_offices is not $null or empty
string. It should be $off_loc -in $main_offices -or $off_loc -in
$corporate_offices
Confirmed this resolved the issue.

Powershell - Azure licence based on ad group

I have been developing AzureAD licence script based on AD Group. So, Find users with a direct assigned, find them in AD, evaluate what group they should be a member of, add them to licensing group. I have hashtable with multiple values $SKUToGroupRev. I can not match hashtable with multiple values with if($ADGroup = $SKUToGroupRev[$SKU.SkuId]) .
From what I want to do :
if there are 18181a46-0d4e-45cd-891e-60aabd171b4e and 0c266dff-15dd-4b49-8397-2bb16070ed52 inside SKUs variable for below command then I will add AD group related to the inside hashtable such as O365_E1_Users
OR
if there are 6fd2c87f-b296-42f0-b197-1e91e994b900 and 0c266dff-15dd-4b49-8397-2bb16070ed52 inside SKUs variable for below command then I will add AD group related to the inside hashtable such as O365_E3_Users
e.g:
# Get licensed SKUs for the user
$aaduser = get-azureaduser -objectID $user.UserPrincipalName
$SKUs = $aaduser | Select UserPrincipalName,ImmutableID -ExpandProperty AssignedLicenses
e.g output:
UserPrincipalName ImmutableId DisabledPlans SKUId
----------------- ----------- ------------- -------------
User01#contoso.com x+MVG6EKEUWHi3r6zjgzCA== {041fe683-03e4-45b6-b1af-c0cdc516da4f... 6fd2c87f-b296-42f0-b197-1e91e994b900
User01#contoso.com x+MVG6EKEUWHi3r6zjgzCA== {} 0c266dff-15dd-4b49-8397-2bb16070ed52
Here is my script :
$CSVfile = "C:\temp\LicenseToGroupUsers.csv"
# Import the CSV file
try {
$users = import-csv $CSVfile
}
catch {
$errorZero = $Error[0]
write-host "Error: " $errorZero -ForegroundColor Red #Writes the latest error
Break
}
write-warning "About to add the following users to license groups for complete SKU:"
foreach ($user in $users){
write-host $user.UserPrincipalName
}
Read-Host -Prompt "Press Enter to continue or CTRL+C to quit"
$e3 = -split "0c266dff-15dd-4b49-8397-2bb16070ed52 6fd2c87f-b296-42f0-b197-1e91e994b900"
$e1 = -split "18181a46-0d4e-45cd-891e-60aabd171b4e 0c266dff-15dd-4b49-8397-2bb16070ed52"
$TEAMS_EXPLORATORY = -split "710779e8-3d4a-4c88-adb9-386c958d1fdf 0c266dff-15dd-4b49-8397-2bb16070ed52"
#$FLOW_FREE_E3 = -split "f30db892-07e9-47e9-837c-80727f46fd3d 6fd2c87f-b296-42f0-b197-1e91e994b900 0c266dff-15dd-4b49-8397-2bb16070ed52"
foreach ($user in $users){
$groupsToAdd = #()
$groupsToRemove = #()
write-host "Processing" $user.UserPrincipalName
# Get licensed SKUs for the user
$aaduser = get-azureaduser -objectID $user.UserPrincipalName
#$SKUs = $aaduser | Select UserPrincipalName,ImmutableID -ExpandProperty AssignedLicenses
#Get the AD ObjectGuid for the group add (cannot use UPN)
$ImmutableID = "" #Null these out otherwise gets reused from previous
#Have to match using the guid
$ImmutableID = $aaduser.ImmutableID
if ($ImmutableID) {$objectGUID = ([GUID][System.Convert]::FromBase64String($ImmutableID)).Guid}
else {
write-warning "Error getting ImmutableID for $UPN, user is likely cloud only, skipping"
Break
}
# test 1
$licenses = $aaduser.AssignedLicenses.SkuId
$is_e1 = !($e1 | ForEach-Object { $licenses.Contains($_) }).Contains($false)
if($is_e1 -eq "True"){
try {
write-host "Adding" $user.UserPrincipalName"to E1Group" -ForegroundColor Green
Write-Host "Test 1: $is_e1"
}
catch {
$errorZero = $Error[0]
write-host "Error: " $errorZero -ForegroundColor Red #Writes the latest error
}
}
$is_e3 = !($e3 | ForEach-Object { $licenses.Contains($_) }).Contains($false)
if($is_e3 -eq "True"){
try {
write-host "Adding" $user.UserPrincipalName"to E3Group" -ForegroundColor Green
Write-Host "Test 3: $is_e3"
}
catch {
$errorZero = $Error[0]
write-host "Error: " $errorZero -ForegroundColor Red #Writes the latest error
}
}
$is_TEAMS_EXPLORATORY = !($TEAMS_EXPLORATORY | ForEach-Object { $licenses.Contains($_) }).Contains($false)
if($is_TEAMS_EXPLORATORY -eq "True"){
try {
write-host "Adding" $user.UserPrincipalName"to (TEAMS_EXPLORATORY)E1Group" -ForegroundColor Green
Write-Host "Test 1: $is_TEAMS_EXPLORATORY"
}
catch {
$errorZero = $Error[0]
write-host "Error: " $errorZero -ForegroundColor Red #Writes the latest error
}
}
<# $is_FLOW_FREE_E3 = !($FLOW_FREE_E3 | ForEach-Object { $licenses.Contains($_) }).Contains($false)
if($is_FLOW_FREE_E3 -eq "True"){
try {
write-host "Adding" $user.UserPrincipalName"to (FLOWFREE)E3Group" -ForegroundColor Green
Write-Host "Test 1: $is_FLOW_FREE_E3"
}
catch {
$errorZero = $Error[0]
write-host "Error: " $errorZero -ForegroundColor Red #Writes the latest error
}
}#>
}
To test agains a combination of SkuID's, using a lookup hashtable as in your first approach is not the easiest way I think. Your current approach looks much better to me, only I would not put the ID's in array variables, but test them literally against the ID's as they are found in the users AssignedLicenses.
Something like this:
$CSVfile = "C:\temp\LicenseToGroupUsers.csv"
# Import the CSV file
$users = Import-Csv -Path $CSVfile
Write-Warning "About to add the following users to license groups for complete SKU:"
$users.UserPrincipalName -join [environment]::NewLine
Write-Host
$answer = Read-Host -Prompt "Press Enter to continue or Q to quit"
if ($answer[0] -eq 'Q') { Clear-Host; exit }
foreach ($user in $users) {
Write-Host "Processing" $user.UserPrincipalName
$ImmutableID = $null # Null these out
$ADGroup = $null
# Get licensed SKUs for the user
$aaduser = Get-AzureADUser -objectID $user.UserPrincipalName
# Get the AD ObjectGuid for the group add (cannot use UPN)
# Have to match using the guid
$ImmutableID = $aaduser.ImmutableID
if (![string]::IsNullOrWhiteSpace($ImmutableID)) {
$objectGUID = ([GUID][System.Convert]::FromBase64String($ImmutableID)).Guid}
else {
Write-Warning "Error getting ImmutableID for $($user.UserPrincipalName), user is likely cloud only, skipping"
continue # skip this one and proceed with the next user
}
$licenses = #($aaduser.AssignedLicenses.SkuId) # force it to be an array
##########################################################################################
# Apparently, SkuId '0c266dff-15dd-4b49-8397-2bb16070ed52' is needed for all combinations,
# so we could already rule out users that do not have that ID in their $licenses..
# if that is indeed the case, you can simplify al other tests by not having to check
# for this ID every time..
# for now, this is an assumption, so commented out.
# if (!($licenses -contains '0c266dff-15dd-4b49-8397-2bb16070ed52')) {
# Write-Warning "Could not determine a group for user $($user.UserPrincipalName)"
# continue # skip this one and proceed with the next user
# }
##########################################################################################
# test E1: 'Microsoft 365 Audio Conferencing' and 'OFFICE 365 E1'
if ($licenses -contains '0c266dff-15dd-4b49-8397-2bb16070ed52' -and
$licenses -contains '18181a46-0d4e-45cd-891e-60aabd171b4e') {
# Add this user to group 'O365_E1_Users'
$ADGroup = 'O365_E1_Users'
}
# test E3: 'Microsoft 365 Audio Conferencing' and 'OFFICE 365 E3'
elseif ($licenses -contains '0c266dff-15dd-4b49-8397-2bb16070ed52' -and
$licenses -contains '6fd2c87f-b296-42f0-b197-1e91e994b900') {
if ($licenses -contains 'f30db892-07e9-47e9-837c-80727f46fd3d') { # also 'MICROSOFT FLOW FREE' ?
# Add this user to group 'FLOW_FREE_E3'
$ADGroup = 'FLOW_FREE_E3'
}
else {
# Add this user to group 'O365_E3_Users'
$ADGroup = 'O365_E3_Users'
}
}
# test 'Microsoft 365 Audio Conferencing' and 'MICROSOFT TEAMS EXPLORATORY'
elseif ($licenses -contains '0c266dff-15dd-4b49-8397-2bb16070ed52' -and
$licenses -contains '710779e8-3d4a-4c88-adb9-386c958d1fdf') {
# Add this user to group 'TEAMS_EXPLORATORY'
$ADGroup = 'TEAMS_EXPLORATORY'
}
# finished the conditions, now see if we can add the user to one of the groups
if (![string]::IsNullOrWhiteSpace($ADGroup)) {
try {
Write-Host "Adding $($user.UserPrincipalName) to $ADGroup" -ForegroundColor Green
# Add-ADGroupMember -Identity $ADGroup -Members $objectGUID
}
catch {
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
}
else {
Write-Warning "Could not determine a group for user $($user.UserPrincipalName)"
}
}

-Contains operator not working powershell

All I'm trying to do is to see if the user input $month is in the array $months. But it's not liking something. Help?
Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = #("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
$month = read-host "Enter the month";
if ($months -Contains $month)
{
write-host "Invalid entry"
$finished = $false
}
else
{
$finished = $true
}
}
You test logic is just not the good one, just reverse youy test or reverse your actions:
Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = #("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
$month = read-host "Enter the month";
if ($months -Contains $month)
{
$finished = $true
}
else
{
write-host "Invalid entry"
$finished = $false
}
}
Instead of using -Contains you should just run a RegEx match using the -Match operator. Or, as you are currently testing for a negative result, use -notmatch instead. You can use your existing code, just modify it a little by joining your months with a pipe character. Like:
Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = #("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
$month = read-host "Enter the month";
if ($month -notmatch ($months -join "|"))
{
write-host "Invalid entry"
$finished = $false
}
else
{
$finished = $true
}
}
Better yet, let's get rid of the If/Else and shorten this. Move the Join to where we define $Months, and then ask for a month and if it isn't a match ask for it again until it is with a While.
$months = #("January", "February","March","April","May","June","July","August","September","October","November","December") -join '|'
$month = read-host "Enter the month"
While($month -notmatch $months){
"Invalid Entry"
$month = read-host "Enter the month"
}

How to clear value of $msg.to in ps1 script?

I have a script for automaticaly notifying users about AD password expiration. It needed for VPN users. But I can't find a way to solve a problem with $msg.to field. It can't accept, for example, "$msg.to = ''" and works only by $msg.to.add method. It makes not so good situation, when user, who was notified first - will recieve all next e-mails because they will be just added at the end of string, but not replacing all of data in $msg.to
There is a code:
Import-Module ActiveDirectory
#SMTP server name
$smtpServer = "mail.domain.local"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
$msgr = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#E-mail structure
Function EmailStructure($to,$expiryDate,$upn)
{
$msg.IsBodyHtml = $true
$msg.From = "notification#domain.com"
$msg.To.Add($to)
$msg.Subject = "Password expiration notice"
$msg.Body = "<html><body><font face='Arial'>This is an automatically generated message from Exchange service.<br><br><b>Please note that the password for your account <i><u>Domain\$upn</u></i> will expire on $expiryDate.</b><br><br>Please change your password immediately or at least before this date as you will be unable to access the service without contacting your administrator.</font></body></html>"
}
Function EmailStructureReport($to)
{
$msgr.IsBodyHtml = $true
$msgr.From = "notification#domain.com"
$msgr.To.Add($to)
$msgr.Subject = "Script running report"
$msgr.Body = "<html><body><font face='Arial'><pre><b>This is a daily report.<br><br>Script has successfully completed its work.<br>$NotificationCounter users have recieved notifications:<br><br>$ListOfAccounts<br><br></b></pre></font></body></html>"
}
#Set the target OU that will be searched for user accounts
$OU = "OU=Organisation,DC=domain,DC=local"
$ADAccounts = Get-ADUser -LDAPFilter "(objectClass=user)" -searchbase $OU -properties PasswordExpired, extensionAttribute15, PasswordNeverExpires, PasswordLastSet, Mail, Enabled | Where-object {$_.Enabled -eq $true -and $_.PasswordNeverExpires -eq $false}
$NotificationCounter = 0
$ListOfAccounts = ""
Foreach ($ADAccount in $ADAccounts)
{
$accountFGPP = Get-ADUserResultantPasswordPolicy $ADAccount
if ($accountFGPP -ne $null)
{
$maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
}
else
{
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
}
#Fill in the user variables
$samAccountName = $ADAccount.samAccountName
$userEmailAddress = $ADAccount.ExtensionAttribute15
$userPrincipalName = $ADAccount.UserPrincipalName
if ($ADAccount.PasswordExpired)
{
Write-host "The password for account $samAccountName has expired!"
}
else
{
$ExpiryDate = $ADAccount.PasswordLastSet + $maxPasswordAgeTimeSpan
$TodaysDate = Get-Date
$DaysToExpire = $ExpiryDate - $TodaysDate
$DaysToExpireDD = $DaysToExpire.ToString() -Split ("\S{17}$")
Write-host "The password for account $samAccountName expires on: $ExpiryDate. Days left: $DaysToExpireDD"
if (($DaysToExpire.Days -eq 15) -or ($DaysToExpire.Days -eq 7) -or ($DaysToExpire.Days -le 3))
{
$expiryDate = $expiryDate.ToString("d",$ci)
#Generate e-mail structure and send message
if ($userEmailAddress)
{
EmailStructure $userEmailAddress $expiryDate $samAccountName
$smtp.Send($msg)
Write-Host "NOTIFICATION - $samAccountName :: e-mail was sent to $userEmailAddress"
$NotificationCounter = $NotificationCounter + 1
$ListOfAccounts = $ListOfAccounts + $samAccountName + " - $DaysToExpireDD days left.<br>"
}
}
}
}
Write-Host "SENDING REPORT TO IT DEPARTMENT"
EmailStructureReport("itdepartment#domain.com")
$smtp.Send($msgr)
How can I drop string in $msg.to after each sent e-mail?
If you want to reuse the same message but change the address and send several times to different addresses, use the clear method on the MailAddressCollection.
So your code will look something like this:
$msg.To.Clear()
$msg.To.Add($to)