Can't send powershell email to managers












0














I'm trying to create a PS script to email managers about employees with expiring accounts(NOT PASSWORDS) within the next 10 days.
I know this has been discussed already a few times but I was unable to find a suitable solution to this issue.



This is what I have so far:



$MyEmail = "email@domain.com"
$SMTP= "domain.com"
$To = "email@domain.com"
$Subject = "Account expiring"
$Body = "Hi_,

the following account is due to expire, please reply to this email if
you wish to extend the account for a further 3 months

Kind regards,

Tech Team"

$Users = Get-ADUser -filter * -SearchBase "OU=Powershell Test
OU,DC=domain,DC=com" -Properties emailaddress,
Manager,accountexpirationdate
$Users | Select
Name,emailaddress,accountexpirationdate,@{label="Manager";expression= .
{(Get-ADUser $_.Manager -Properties emailaddress).emailaddress}}

Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Body $Body
-SmtpServer $SMTP


I believe I am missing a few pieces.
Can anyone help?
It would be much appreciated.



Thanks










share|improve this question




















  • 2




    You didn't mention the error you get .
    – Prasoon Karunan V
    Nov 21 '18 at 12:51








  • 1




    The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
    – Matt
    Nov 21 '18 at 13:14












  • Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
    – Allan
    Nov 21 '18 at 13:56
















0














I'm trying to create a PS script to email managers about employees with expiring accounts(NOT PASSWORDS) within the next 10 days.
I know this has been discussed already a few times but I was unable to find a suitable solution to this issue.



This is what I have so far:



$MyEmail = "email@domain.com"
$SMTP= "domain.com"
$To = "email@domain.com"
$Subject = "Account expiring"
$Body = "Hi_,

the following account is due to expire, please reply to this email if
you wish to extend the account for a further 3 months

Kind regards,

Tech Team"

$Users = Get-ADUser -filter * -SearchBase "OU=Powershell Test
OU,DC=domain,DC=com" -Properties emailaddress,
Manager,accountexpirationdate
$Users | Select
Name,emailaddress,accountexpirationdate,@{label="Manager";expression= .
{(Get-ADUser $_.Manager -Properties emailaddress).emailaddress}}

Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Body $Body
-SmtpServer $SMTP


I believe I am missing a few pieces.
Can anyone help?
It would be much appreciated.



Thanks










share|improve this question




















  • 2




    You didn't mention the error you get .
    – Prasoon Karunan V
    Nov 21 '18 at 12:51








  • 1




    The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
    – Matt
    Nov 21 '18 at 13:14












  • Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
    – Allan
    Nov 21 '18 at 13:56














0












0








0







I'm trying to create a PS script to email managers about employees with expiring accounts(NOT PASSWORDS) within the next 10 days.
I know this has been discussed already a few times but I was unable to find a suitable solution to this issue.



This is what I have so far:



$MyEmail = "email@domain.com"
$SMTP= "domain.com"
$To = "email@domain.com"
$Subject = "Account expiring"
$Body = "Hi_,

the following account is due to expire, please reply to this email if
you wish to extend the account for a further 3 months

Kind regards,

Tech Team"

$Users = Get-ADUser -filter * -SearchBase "OU=Powershell Test
OU,DC=domain,DC=com" -Properties emailaddress,
Manager,accountexpirationdate
$Users | Select
Name,emailaddress,accountexpirationdate,@{label="Manager";expression= .
{(Get-ADUser $_.Manager -Properties emailaddress).emailaddress}}

Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Body $Body
-SmtpServer $SMTP


I believe I am missing a few pieces.
Can anyone help?
It would be much appreciated.



Thanks










share|improve this question















I'm trying to create a PS script to email managers about employees with expiring accounts(NOT PASSWORDS) within the next 10 days.
I know this has been discussed already a few times but I was unable to find a suitable solution to this issue.



This is what I have so far:



$MyEmail = "email@domain.com"
$SMTP= "domain.com"
$To = "email@domain.com"
$Subject = "Account expiring"
$Body = "Hi_,

the following account is due to expire, please reply to this email if
you wish to extend the account for a further 3 months

Kind regards,

Tech Team"

$Users = Get-ADUser -filter * -SearchBase "OU=Powershell Test
OU,DC=domain,DC=com" -Properties emailaddress,
Manager,accountexpirationdate
$Users | Select
Name,emailaddress,accountexpirationdate,@{label="Manager";expression= .
{(Get-ADUser $_.Manager -Properties emailaddress).emailaddress}}

Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Body $Body
-SmtpServer $SMTP


I believe I am missing a few pieces.
Can anyone help?
It would be much appreciated.



Thanks







powershell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 14:13

























asked Nov 21 '18 at 12:49









Allan

61




61








  • 2




    You didn't mention the error you get .
    – Prasoon Karunan V
    Nov 21 '18 at 12:51








  • 1




    The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
    – Matt
    Nov 21 '18 at 13:14












  • Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
    – Allan
    Nov 21 '18 at 13:56














  • 2




    You didn't mention the error you get .
    – Prasoon Karunan V
    Nov 21 '18 at 12:51








  • 1




    The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
    – Matt
    Nov 21 '18 at 13:14












  • Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
    – Allan
    Nov 21 '18 at 13:56








2




2




You didn't mention the error you get .
– Prasoon Karunan V
Nov 21 '18 at 12:51






You didn't mention the error you get .
– Prasoon Karunan V
Nov 21 '18 at 12:51






1




1




The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
– Matt
Nov 21 '18 at 13:14






The formatting of that code would create errors. Is that exactly how you are running your code? For example you have a period after the variable $to is declared and a select that is broken across two lines and a calculated property that has a extra period in it?
– Matt
Nov 21 '18 at 13:14














Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
– Allan
Nov 21 '18 at 13:56




Hi Matt, Thank you for you reply. I've noticed the full stop ... It was added when I've pasted the content. Also the SELECT is splitted only because it was pasted in that manner, it is actually a one line.
– Allan
Nov 21 '18 at 13:56












1 Answer
1






active

oldest

votes


















0














So I've edited my previous comment, because I couldn't stand that is was still not very good:



$MyEmail = "email@domain.com"
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$SMTP= "domain.com"
$SMTPPort = "587"
$cred = New-Object System.Management.Automation.PSCredential ($MyEmail, $secpasswd)

$NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(0);
$ExpireMax = (Get-Date).AddDays(90);
$today = (Get-Date)

try{
$expiringsoon = Get-ADUser -Filter * -SearchBase "OU=Powershell Test OU,DC=domain,DC=com" -Properties accountExpires | Where-Object {$_.accountExpires -ne $NeverExpires -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
}catch{
throw $_
}
foreach($user in $expiringsoon){
try{
$userDetails = Get-ADUser $user -Properties AccountExpirationDate,accountExpires,manager
}catch{
Write-Host "Error while searching for user '$user'" -ForegroundColor Red
}
$ExpiryDate = $userDetails.AccountExpirationDate
$DaysLeft = ($ExpiryDate-$today).days
$DateStr = $ExpiryDate.AddDays(-1).ToString("dd/MM/yyyy")
$name = $user.Name
$manager = $userDetails.manager
try{
$managerEmail = (Get-ADUser $manager -Properties emailAddress).emailAddress
if(!$managerEmail){
$managerEmail = $MyEmail
}
}catch{
$managerEmail = $MyEmail
}

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $DaysLeft

if (($DaysLeft) -gt "1")
{
$messageDays = "in " + "$DaysLeft" + " days"
}
ElseIf (($DaysLeft) -eq "1")
{
$messageDays = "in 1 day"
}
else
{
$messageDays = "today"
}


# Email Subject Set Here
$subject="The account of $name will expire $messageDays "

# Email Body Set Here, Note You can use HTML, including Images.
$body ="
Hi,
<p>the following account '$name' is due to expire, please reply to this email if you wish to extend the account for a further 3 months<br>
<p>Kind regards, <br>
Tech Team
</P>"

#----- Show Details of sent mail -----#
try{
Send-MailMessage -to $managerEmail -from $MyEmail -SmtpServer $SMTP -subject $subject -body $body -bodyasHTML -priority High –Credential $cred -port $SMTPPort -UseSsl
Write-Host "An e-mail has been send to $managerEmail about $name" -ForegroundColor Green
}catch{
Write-Host "Email to $managerEmail for $name failed with error: $($_.exception.message)" -ForegroundColor Red
}
}


Okay, because I couldn't help but wanting to get the script right. Here my present to you. A perfectly working script that sends emails to managers of whom the user expires within 90 days. I also included error handling. Please take this script as a guide to create your own and if you have any questions, feel free.






share|improve this answer



















  • 1




    Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
    – Scepticalist
    Nov 21 '18 at 13:38










  • Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
    – Allan
    Nov 21 '18 at 14:35










  • This is not for expiring passwords, but expiring accounts. So might still be useful ;)
    – Bernard Moeskops
    Nov 21 '18 at 14:55










  • Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
    – Allan
    Nov 21 '18 at 17:34










  • Glad to help! Thanks for letting me know :)
    – Bernard Moeskops
    Nov 21 '18 at 20:31











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412397%2fcant-send-powershell-email-to-managers%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














So I've edited my previous comment, because I couldn't stand that is was still not very good:



$MyEmail = "email@domain.com"
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$SMTP= "domain.com"
$SMTPPort = "587"
$cred = New-Object System.Management.Automation.PSCredential ($MyEmail, $secpasswd)

$NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(0);
$ExpireMax = (Get-Date).AddDays(90);
$today = (Get-Date)

try{
$expiringsoon = Get-ADUser -Filter * -SearchBase "OU=Powershell Test OU,DC=domain,DC=com" -Properties accountExpires | Where-Object {$_.accountExpires -ne $NeverExpires -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
}catch{
throw $_
}
foreach($user in $expiringsoon){
try{
$userDetails = Get-ADUser $user -Properties AccountExpirationDate,accountExpires,manager
}catch{
Write-Host "Error while searching for user '$user'" -ForegroundColor Red
}
$ExpiryDate = $userDetails.AccountExpirationDate
$DaysLeft = ($ExpiryDate-$today).days
$DateStr = $ExpiryDate.AddDays(-1).ToString("dd/MM/yyyy")
$name = $user.Name
$manager = $userDetails.manager
try{
$managerEmail = (Get-ADUser $manager -Properties emailAddress).emailAddress
if(!$managerEmail){
$managerEmail = $MyEmail
}
}catch{
$managerEmail = $MyEmail
}

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $DaysLeft

if (($DaysLeft) -gt "1")
{
$messageDays = "in " + "$DaysLeft" + " days"
}
ElseIf (($DaysLeft) -eq "1")
{
$messageDays = "in 1 day"
}
else
{
$messageDays = "today"
}


# Email Subject Set Here
$subject="The account of $name will expire $messageDays "

# Email Body Set Here, Note You can use HTML, including Images.
$body ="
Hi,
<p>the following account '$name' is due to expire, please reply to this email if you wish to extend the account for a further 3 months<br>
<p>Kind regards, <br>
Tech Team
</P>"

#----- Show Details of sent mail -----#
try{
Send-MailMessage -to $managerEmail -from $MyEmail -SmtpServer $SMTP -subject $subject -body $body -bodyasHTML -priority High –Credential $cred -port $SMTPPort -UseSsl
Write-Host "An e-mail has been send to $managerEmail about $name" -ForegroundColor Green
}catch{
Write-Host "Email to $managerEmail for $name failed with error: $($_.exception.message)" -ForegroundColor Red
}
}


Okay, because I couldn't help but wanting to get the script right. Here my present to you. A perfectly working script that sends emails to managers of whom the user expires within 90 days. I also included error handling. Please take this script as a guide to create your own and if you have any questions, feel free.






share|improve this answer



















  • 1




    Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
    – Scepticalist
    Nov 21 '18 at 13:38










  • Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
    – Allan
    Nov 21 '18 at 14:35










  • This is not for expiring passwords, but expiring accounts. So might still be useful ;)
    – Bernard Moeskops
    Nov 21 '18 at 14:55










  • Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
    – Allan
    Nov 21 '18 at 17:34










  • Glad to help! Thanks for letting me know :)
    – Bernard Moeskops
    Nov 21 '18 at 20:31
















0














So I've edited my previous comment, because I couldn't stand that is was still not very good:



$MyEmail = "email@domain.com"
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$SMTP= "domain.com"
$SMTPPort = "587"
$cred = New-Object System.Management.Automation.PSCredential ($MyEmail, $secpasswd)

$NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(0);
$ExpireMax = (Get-Date).AddDays(90);
$today = (Get-Date)

try{
$expiringsoon = Get-ADUser -Filter * -SearchBase "OU=Powershell Test OU,DC=domain,DC=com" -Properties accountExpires | Where-Object {$_.accountExpires -ne $NeverExpires -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
}catch{
throw $_
}
foreach($user in $expiringsoon){
try{
$userDetails = Get-ADUser $user -Properties AccountExpirationDate,accountExpires,manager
}catch{
Write-Host "Error while searching for user '$user'" -ForegroundColor Red
}
$ExpiryDate = $userDetails.AccountExpirationDate
$DaysLeft = ($ExpiryDate-$today).days
$DateStr = $ExpiryDate.AddDays(-1).ToString("dd/MM/yyyy")
$name = $user.Name
$manager = $userDetails.manager
try{
$managerEmail = (Get-ADUser $manager -Properties emailAddress).emailAddress
if(!$managerEmail){
$managerEmail = $MyEmail
}
}catch{
$managerEmail = $MyEmail
}

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $DaysLeft

if (($DaysLeft) -gt "1")
{
$messageDays = "in " + "$DaysLeft" + " days"
}
ElseIf (($DaysLeft) -eq "1")
{
$messageDays = "in 1 day"
}
else
{
$messageDays = "today"
}


# Email Subject Set Here
$subject="The account of $name will expire $messageDays "

# Email Body Set Here, Note You can use HTML, including Images.
$body ="
Hi,
<p>the following account '$name' is due to expire, please reply to this email if you wish to extend the account for a further 3 months<br>
<p>Kind regards, <br>
Tech Team
</P>"

#----- Show Details of sent mail -----#
try{
Send-MailMessage -to $managerEmail -from $MyEmail -SmtpServer $SMTP -subject $subject -body $body -bodyasHTML -priority High –Credential $cred -port $SMTPPort -UseSsl
Write-Host "An e-mail has been send to $managerEmail about $name" -ForegroundColor Green
}catch{
Write-Host "Email to $managerEmail for $name failed with error: $($_.exception.message)" -ForegroundColor Red
}
}


Okay, because I couldn't help but wanting to get the script right. Here my present to you. A perfectly working script that sends emails to managers of whom the user expires within 90 days. I also included error handling. Please take this script as a guide to create your own and if you have any questions, feel free.






share|improve this answer



















  • 1




    Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
    – Scepticalist
    Nov 21 '18 at 13:38










  • Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
    – Allan
    Nov 21 '18 at 14:35










  • This is not for expiring passwords, but expiring accounts. So might still be useful ;)
    – Bernard Moeskops
    Nov 21 '18 at 14:55










  • Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
    – Allan
    Nov 21 '18 at 17:34










  • Glad to help! Thanks for letting me know :)
    – Bernard Moeskops
    Nov 21 '18 at 20:31














0












0








0






So I've edited my previous comment, because I couldn't stand that is was still not very good:



$MyEmail = "email@domain.com"
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$SMTP= "domain.com"
$SMTPPort = "587"
$cred = New-Object System.Management.Automation.PSCredential ($MyEmail, $secpasswd)

$NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(0);
$ExpireMax = (Get-Date).AddDays(90);
$today = (Get-Date)

try{
$expiringsoon = Get-ADUser -Filter * -SearchBase "OU=Powershell Test OU,DC=domain,DC=com" -Properties accountExpires | Where-Object {$_.accountExpires -ne $NeverExpires -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
}catch{
throw $_
}
foreach($user in $expiringsoon){
try{
$userDetails = Get-ADUser $user -Properties AccountExpirationDate,accountExpires,manager
}catch{
Write-Host "Error while searching for user '$user'" -ForegroundColor Red
}
$ExpiryDate = $userDetails.AccountExpirationDate
$DaysLeft = ($ExpiryDate-$today).days
$DateStr = $ExpiryDate.AddDays(-1).ToString("dd/MM/yyyy")
$name = $user.Name
$manager = $userDetails.manager
try{
$managerEmail = (Get-ADUser $manager -Properties emailAddress).emailAddress
if(!$managerEmail){
$managerEmail = $MyEmail
}
}catch{
$managerEmail = $MyEmail
}

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $DaysLeft

if (($DaysLeft) -gt "1")
{
$messageDays = "in " + "$DaysLeft" + " days"
}
ElseIf (($DaysLeft) -eq "1")
{
$messageDays = "in 1 day"
}
else
{
$messageDays = "today"
}


# Email Subject Set Here
$subject="The account of $name will expire $messageDays "

# Email Body Set Here, Note You can use HTML, including Images.
$body ="
Hi,
<p>the following account '$name' is due to expire, please reply to this email if you wish to extend the account for a further 3 months<br>
<p>Kind regards, <br>
Tech Team
</P>"

#----- Show Details of sent mail -----#
try{
Send-MailMessage -to $managerEmail -from $MyEmail -SmtpServer $SMTP -subject $subject -body $body -bodyasHTML -priority High –Credential $cred -port $SMTPPort -UseSsl
Write-Host "An e-mail has been send to $managerEmail about $name" -ForegroundColor Green
}catch{
Write-Host "Email to $managerEmail for $name failed with error: $($_.exception.message)" -ForegroundColor Red
}
}


Okay, because I couldn't help but wanting to get the script right. Here my present to you. A perfectly working script that sends emails to managers of whom the user expires within 90 days. I also included error handling. Please take this script as a guide to create your own and if you have any questions, feel free.






share|improve this answer














So I've edited my previous comment, because I couldn't stand that is was still not very good:



$MyEmail = "email@domain.com"
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$SMTP= "domain.com"
$SMTPPort = "587"
$cred = New-Object System.Management.Automation.PSCredential ($MyEmail, $secpasswd)

$NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(0);
$ExpireMax = (Get-Date).AddDays(90);
$today = (Get-Date)

try{
$expiringsoon = Get-ADUser -Filter * -SearchBase "OU=Powershell Test OU,DC=domain,DC=com" -Properties accountExpires | Where-Object {$_.accountExpires -ne $NeverExpires -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
}catch{
throw $_
}
foreach($user in $expiringsoon){
try{
$userDetails = Get-ADUser $user -Properties AccountExpirationDate,accountExpires,manager
}catch{
Write-Host "Error while searching for user '$user'" -ForegroundColor Red
}
$ExpiryDate = $userDetails.AccountExpirationDate
$DaysLeft = ($ExpiryDate-$today).days
$DateStr = $ExpiryDate.AddDays(-1).ToString("dd/MM/yyyy")
$name = $user.Name
$manager = $userDetails.manager
try{
$managerEmail = (Get-ADUser $manager -Properties emailAddress).emailAddress
if(!$managerEmail){
$managerEmail = $MyEmail
}
}catch{
$managerEmail = $MyEmail
}

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $DaysLeft

if (($DaysLeft) -gt "1")
{
$messageDays = "in " + "$DaysLeft" + " days"
}
ElseIf (($DaysLeft) -eq "1")
{
$messageDays = "in 1 day"
}
else
{
$messageDays = "today"
}


# Email Subject Set Here
$subject="The account of $name will expire $messageDays "

# Email Body Set Here, Note You can use HTML, including Images.
$body ="
Hi,
<p>the following account '$name' is due to expire, please reply to this email if you wish to extend the account for a further 3 months<br>
<p>Kind regards, <br>
Tech Team
</P>"

#----- Show Details of sent mail -----#
try{
Send-MailMessage -to $managerEmail -from $MyEmail -SmtpServer $SMTP -subject $subject -body $body -bodyasHTML -priority High –Credential $cred -port $SMTPPort -UseSsl
Write-Host "An e-mail has been send to $managerEmail about $name" -ForegroundColor Green
}catch{
Write-Host "Email to $managerEmail for $name failed with error: $($_.exception.message)" -ForegroundColor Red
}
}


Okay, because I couldn't help but wanting to get the script right. Here my present to you. A perfectly working script that sends emails to managers of whom the user expires within 90 days. I also included error handling. Please take this script as a guide to create your own and if you have any questions, feel free.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 14:15

























answered Nov 21 '18 at 13:34









Bernard Moeskops

22316




22316








  • 1




    Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
    – Scepticalist
    Nov 21 '18 at 13:38










  • Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
    – Allan
    Nov 21 '18 at 14:35










  • This is not for expiring passwords, but expiring accounts. So might still be useful ;)
    – Bernard Moeskops
    Nov 21 '18 at 14:55










  • Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
    – Allan
    Nov 21 '18 at 17:34










  • Glad to help! Thanks for letting me know :)
    – Bernard Moeskops
    Nov 21 '18 at 20:31














  • 1




    Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
    – Scepticalist
    Nov 21 '18 at 13:38










  • Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
    – Allan
    Nov 21 '18 at 14:35










  • This is not for expiring passwords, but expiring accounts. So might still be useful ;)
    – Bernard Moeskops
    Nov 21 '18 at 14:55










  • Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
    – Allan
    Nov 21 '18 at 17:34










  • Glad to help! Thanks for letting me know :)
    – Bernard Moeskops
    Nov 21 '18 at 20:31








1




1




Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
– Scepticalist
Nov 21 '18 at 13:38




Best practice would also not use -Filter * - the following will get accounts that actually have an expiry date: Get-ADUser -Filter 'AccountExpirationDate -like "*"'
– Scepticalist
Nov 21 '18 at 13:38












Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
– Allan
Nov 21 '18 at 14:35




Hi Bernard, Thank you for you reply. However I don't need it for the expiring passwords.
– Allan
Nov 21 '18 at 14:35












This is not for expiring passwords, but expiring accounts. So might still be useful ;)
– Bernard Moeskops
Nov 21 '18 at 14:55




This is not for expiring passwords, but expiring accounts. So might still be useful ;)
– Bernard Moeskops
Nov 21 '18 at 14:55












Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
– Allan
Nov 21 '18 at 17:34




Hi Bernard, This has worked like a charm. However I had to remove the SMTPport, we couldn't access the remote server. Brilliant! Thank you very much! Best Regards
– Allan
Nov 21 '18 at 17:34












Glad to help! Thanks for letting me know :)
– Bernard Moeskops
Nov 21 '18 at 20:31




Glad to help! Thanks for letting me know :)
– Bernard Moeskops
Nov 21 '18 at 20:31


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412397%2fcant-send-powershell-email-to-managers%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'