Author Posts

August 22, 2017 at 10:31 pm

Hi,

I'm trying to pull together a script that looks at AD, checks for accounts that are expiring within the next 30 days, and send an email to their manager, with the expiring account name and expiration date.

I've pulled together some components, but I can't get it to come together;

$OU1 = "OU=Departments,DC=domain,DC=com"
$expiredays = 30
$expiredaccounts = Search-ADAccount -SearchBase "$OU" -AccountExpiring -TimeSpan "$expiredays"

ForEach ($user in $expiredaccounts){
$userAccountName = $user.SamAccountName
#$accountexpire = $user.AccountExpirationDate
get-aduser $userAccountName -properties * | select Name,sAMAccountName,AccountExpirationDate,Manager
}

I can bring back all the info I need, but I don't know how to pull the manager's email address from the Manager's object, and ultimately put it all together in an email.

Any help is appreciated.
Thanks so much.

August 22, 2017 at 10:56 pm

Here is how you can get an AD user's e-mail address.

$MangerAddr = (Get-ADUser -Identity Manager -Properties EmailAddress).EmailAddress

You can use the Send-MailMessage cmdlet to send the message. This, and getting the manager's e-mail address all goes within your ForEach block.

August 22, 2017 at 11:25 pm

Here is something made for our team before we started using manage engine. It's code pirated from other peoples examples and then put together. I run it in the elevated ISE. I cannot remember if the email part works correctly, but it should be simple enough to change where it is sent. It's from two years ago, so it is probably more complicated than it should be.

Search for and change the following lines to meet your needs

YOUR DC INFO
http://whereyouchangeyourpassword

cls


# All variables that exists at this moment will also exist

# after executing “Cleanup-Variables”

 

###################################################################

# stores all existing variable names in the variable

# “startupVariables”. This variable itself will be

# removed too.

 

$startupVariables=””

new-variable -force -name startupVariables -value ( Get-Variable |

   % { $_.Name } )

 

function Cleanup-Variables {

  Get-Variable |

    Where-Object { $startupVariables -notcontains $_.Name } |

    % { Remove-Variable -Name “$($_.Name)” -Force -Scope “global” }

}

 

####################################################################

# Place your profile scripts in here
#Sample: –>

$myVariable = (Get-Process | select -first 5)

 

write-host “Here the variable exists”

$myVariable

#< –

#Script



write-host `n
write-host `n
write-host `n
write-host `n
Write-Host "DATA BEGINS BELOW"
Write-Host "**********************************************"


write-host `n
write-host `n




####################################################################
####################################################################
####################################################################
####################################################################




Function WhipItGood

{

$Users = Get-AdUser -Filter {Enabled -eq $true} -SearchBase "YOUR DC INFO" -Properties *
$maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days


ForEach ($User in $Users)
{
Set-ADUser $User -Clear ipPhone
$Name = "Name"
$Username = @{Name  = "User Name"; Expression={($user."SamAccountName")}}
$PasswordDaysLeft2 = (([datetime]::FromFileTime((Get-ADUser $User -Properties "msDS-UserPasswordExpiryTimeComputed")."msDS-UserPasswordExpiryTimeComputed"))-(Get-Date)).Days
$SetIpPhone = Set-Aduser $User -Replace @{ipPhone = $PasswordDaysLeft2}
$PasswordDaysLeft = @{Name = "Days Until Password Expires"; Expression={($User."ipPhone")}}
#Start-Sleep -s 3
$Description = @{Name = "Account Description"; Expression={($user."Description")}}
$Email = @{Name = "Email Address"; Expression={($user."mail")}}
$Enabled = @{Name = "Is The Account Active"; Expression={($user."Enabled")}}
$LastLogon = @{Name = "User Last Computer Logon Date"; Expression={($user."LastLogonDate")}}
$DisabledOn = @{Name = "Account Will Be Disabled On"; Expression={($user."AccountExpirationDate")}}
$PasswordExpired = @{Name = "Is The Password Expired"; Expression={($user."PasswordExpired")}}
$PasswordLastChanged = @{Name = "Password Last Changed On"; Expression={($user."PasswordLastSet")}}
$PasswordExpireDate = @{Name ="Password Expires On";Expression={$user.PasswordLastSet.AddDays($maxPasswordAge)}}


Get-Aduser $user -properties * | Select $Name , 
                                        $Username, 
                                        $Description,
                                        $Email, 
                                        $PasswordDaysLeft,
                                        $PasswordExpireDate, 
                                        $PasswordLastChanged,
                                        $PasswordExpired,
                                        $LastLogon,
                                        $Enabled, 
                                        $DisabledOn

Get-Aduser $user -properties * | Select $Name , 
                                        $Username, 
                                        $Description,
                                        $Email, 
                                        $PasswordDaysLeft,
                                        $PasswordExpireDate, 
                                        $PasswordLastChanged,
                                        $PasswordExpired,
                                        $LastLogon,
                                        $Enabled, 
                                        $DisabledOn | export-csv -append "$env:USERPROFILE\desktop\Expiring-Unsorted.csv" -NoTypeInformation




}
}





Function EmaleDemBombaClots

{

$AyeImpawts = Import-csv $env:USERPROFILE\desktop\PasswordsExpiring.csv
ForEach ($AyeImpawt in $AyeImpawts | where {$_."Days Until Password Expires" -le 10})


{
$WhoDis = $AyeImpawt.Name
$DaUsawName = $AyeImpawt.("User Name")
$HeeeMail = $AyeImpawt."Email Address"
$DaysTillGwon = $AyeImpawt.("Days Until Password Expires")
$WenGwonExpiyaDate = $AyeImpawt.("Password Expires On")
$WenGwonExpiyaDateFawm = $WenGwonExpiyaDate.Split(' ') | Select -First 1







 
 		$ol = New-Object -comObject Outlook.Application
		
		$mail = $ol.CreateItem(0)
		
		$Mail.Recipients.Add($HeeeMail)
		
		$Mail.Subject = "Your Domain Password Will Expire in $DaysTillGwon Days"
		
		$Mail.Body = "
 





Hello $WhoDis,

Your password will expire in $DaysTillGwon days, on $WenGwonExpiyaDateFawm

 

You can change your password at http://whereyouchangeyourpassword
Log in and change your password with the usename and your email we have on file below.

Your User Name is: $DaUsawName
Your Email Address is: $HeeeMail

Remember, your current password will expire in $DaysTillGwon days on $WenGwonExpiyaDateFawm

Please change it as soon as you can. 






Thank you, 

$IBeeDisMon


"

                
		
		$Mail.save()
		
		$inspector = $mail.GetInspector
		$inspector.Display()
		
}

}

#Variables are placed inside function for convenience





# Disable Error Messages
$errpref = $ErrorActionPreference #save actual preference
$ErrorActionPreference = "silentlycontinue"



# Remove CSV's from desktop file if it exists
Remove-Item "$env:USERPROFILE\desktop\Expiring-Unsorted.csv" -Force
Remove-Item "$env:USERPROFILE\desktop\Expiring.csv"          -Force


# Re-enable Error Messages
$ErrorActionPreference = $errpref 



# Run Function to grab users information
#   and export it to a CSV file with no type header
WhipitGood



# Import and Sort on Days Until Password Expires
#    Export to Final Name
Import-Csv "$env:USERPROFILE\desktop\PasswordsExpiring-Unsorted.csv" | 
       Sort-Object @{e={$_."Days Until Password Expires" -as [int]}} | 
            Export-CSV "$env:USERPROFILE\desktop\PasswordsExpiring.csv" -NoTypeInformation


# Delete The Old Exported File
Remove-Item  "$env:USERPROFILE\desktop\PasswordsExpiring-Unsorted.csv"

# Open CSV file in Excel
Invoke-Item "$env:USERPROFILE\desktop\PasswordsExpiring.csv"


# Run Function To Email Users
#EmaleDemBombaClots












write-host `n
write-host `n

Write-Host "**********************************************"
Write-host "DATA ENDS"

write-host `n
write-host `n
####################################################################

# Now all variables created since execution of line 8 will

# be removed.

 

Cleanup-Variables

 

####################################################################

 

#Sample: –>

write-host “Now the variable is unknown”

$myVariable

#< 

August 23, 2017 at 7:17 am

I wrote one like this a couple of years ago. I will did it out and post tonight

August 23, 2017 at 8:38 am

Just found a post about the script I was modifying to do this. The original script was by Mike Laughlins
https://social.technet.microsoft.com/Forums/en-US/b095a70e-d3f0-47cb-9438-ad64fa259a34/extensionattribute6?forum=winserverpowershell

I will try and dig out the finished script tonight as I dont have it on me at the moment but this should get you going