this is my first try in Powershell and I have to say I have no Idea what I am doing.
So I want to create a Script, that when it runs send an E-Mail to an Admin with a li
If the user property accountExpires
equals to 0 or 9223372036854775807, then the account never expires.
To get a list of accounts that are expiring within a certain number of days, you an do:
$refDate = (Get-Date).AddDays(30)
$expiringUsers = Get-ADUser -Filter 'Enabled -eq $true' -SearchBase "CN=Users,DC=mydomain,DC=de" -Properties AccountExpirationDate, accountExpires |
Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and ($_.AccountExpirationDate -le $refDate)} |
Select-Object Name, DistinguishedName, AccountExpirationDate
Next, you need to send this to an admin by email.
There are various ways of doing this of course, below example sends the result as CSV attachment.
# don't send mail if there are no expiring users found
if ($expiringUsers.Count) {
# write the results to csv file
$outFile = Join-Path -Path $env:TEMP -ChildPath ('{0:yyyy-MM-dd}_ExpiringUsers.csv' -f (Get-Date))
$expiringUsers | Export-Csv -Path $outFile -NoTypeInformation
# use splatting for cmdlets that take a lot of parameters
$mailParams = @{
SmtpServer = 'smtp.fabrikam.com'
From = 'troi@fabrikam.com'
To = 'admin@fabrikam.com'
Subject = 'Expiring user accounts'
Body = 'Please find the list of expiring user accounts in the attachment'
Attachments = $outFile
# See https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage
# for more parameters you might want to use
}
Send-Mailmessage @mailParams
Write-Host "$($expiringUsers.Count) user accounts are set to expire within the next 30 days. An email has been sent."
}
else {
Write-Host 'No user accounts are set to expire within the next 30 days'
}
Get-ADUser
by default returns these properties: DistinguishedName
,Enabled
,GivenName
,Name
,ObjectClass
,ObjectGUID
,SamAccountName
,SID
,Surname
and UserPrincipalName
.
Property AccountExpirationDate
is the value of property accountExpires
converted to local time.
To select users you need do like this
Get-ADUser -Filter 'enabled -eq $true' -SearchBase "CN=Users, DC=mydomain, DC=de" -Properties AccountExpirationDate|
Where-Object {($_.Accountexpirationdate -le (get-date).AddDays(30)) -and ($_.Accountexpirationdate -ne $null)}
First you must select property what you want, then you piping your object to Where-Object
and filtering your property. When you filter it you must check that field is not null because users with unlimited expiration have this field value $null
, and your user field $_.Accountexpirationdate
must be lesser or equal currentdate+30 days.
You can select needed fields after that and save you result to variable.Then you can send it via email.