• I  have modified the code to look like this but I am getting errors , Code I am using is below the errors.

    Cannot convert argument "fileTime", with value: "12/25/2021 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert 
    value "12/25/2021 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
    At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5
    + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
    
    Cannot convert argument "fileTime", with value: "12/01/2019 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert 
    value "12/01/2019 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
    At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5
    + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
    
    Cannot convert argument "fileTime", with value: "12/01/2019 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert 
    value "12/01/2019 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
    At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5
    + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

    -----------------------------------------

    Code I am using is shown below

    ----------------------------------

    # sort-object -property 'PwdLastSet'

    #$PasswordExp = $users.PasswordLastSet.Addyears(1) I don't think this is really what you are looking for; adding a year means they will never match

    #$MailParams = @{
    # To = $users.name
    # From = 'Faiz.Qureshi@mail.toronto.ca'
    # SMTPServer = 'mail.toronto.ca'
    # Subject = 'Password Expiration warning'
    #}

    #$AdminMailParams = @{
    # To = 'iq@mail.cc'
    # From = 'iq@mail.cc'
    # SMTPServer = 'mail.cc'
    # Subject = 'Password Expiration warning list'
    # Attachments = 'C:TempPasswordExpList.txt'
    #}

    foreach ($user in $Users) {
    #Thinking about this part - because you are using -eq comparisons, this setup forcibly returns the midnight stamp, just like the initial warning variables do;
    #otherwise, you're dealing with 100 nanosecond ticks, and that would be virtually impossible to be equal
    #I'm also assuming you are defining the Email stubs somewhere else
    $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.AccountExpirationDate).ToString('yyyy-MM-dd'))
    $username = $user.name
    $Message = 'User ({0}) has a password expiration date of {0}' -f $username, $PasswordExp.ToLongDateString()
    Add-Content -Path C:TempPasswordExpList.txt -Value $Message

    switch ($PasswordExp) {
    ($PasswordExp -eq $OneDayWarnDate) {
    $WarningDays = '1'
    $WarningDate = $OneDayWarnDate
    # You are overwriting your own variable here with the $file statements, this does not make sense?
    $VerboseMessage = 'The password expiration for user {0} is within the OneDayWarnBlock' -f $AccountExpirationDate
    break
    }
    ($PasswordExp -eq $SevenWarnDate) {
    $WarningDays = '7'
    $WarningDate = $SevenDayWarnDate
    $VerboseMessage = 'The password expiration for user {0} is within the SevenDayWarnBlock' -f $AccountExpirationDate
    break
    }
    ($PasswordExp -eq $FifteenDayWarnDate) {
    $WarningDays = '15'
    $WarningDate = $FifteenDayWarnDate
    $VerboseMessage = 'The password expiration for user {0} is within the FifteenDayWarnBlock' -f $AccountExpirationDate
    break
    }
    ($PasswordExp -eq $ThirtyDayWarnDate) {
    $WarningDays = '30'
    $WarningDate = $ThirtyDayWarnDate
    $VerboseMessage = 'The password expiration for user {0} is within the ThirtyDayWarnBlock' -f $AccountExpirationDate
    break
    }
    }}
    # Write-Verbose -Message $VerboseMessage
    # $MailParams.Add('Body', ($EmailStub1, $users.name, $EmailStub2, $WarningDays, $EmailStub3, $WarningDate.ToString('yyyy-MM-dd'), $EmailStub4 -join ' ')) )
    # Send-MailMessage $MailParams

    #Send-MailMessage @AdminMailParams

    0
  • Hi David,

    If I use this command I am seeing the passwd last set values under AccountExprationDate , what is the difference between this and the previous command. Also is there a way I can substitute the nulls in AccountExprationDate   with a sysdate ?

    Get-ADUser -Filter 'enabled -eq $true' -Properties AccountExpirationDate |
    Select sAMAccountName, distinguishedName, AccountExpirationDate

    0
  • Hi David,

    I was able to fix the issue I had described in my reply and the code is now working, I am able to output username , PwdLastSet values to the output file, I will look into the email stub part later.

    I have a problem though, looks like the PwdLastSet column is always null as they have not stored this information,  as I mentioned earlier, I was using PwdLastSet and adding a year to it to get the password expiry date information as our AD was not letting us retrieve this information , so is there any other way for me to get the password expiry information ?

     

    Thanks

    IQ

     

    0
  • Thanks David, for taking time to look into this piece of code for me.

    Please ignore the $File pieces in the code , I was just playing with the syntax to familiarise myself.

    With regards to PassWdEXp being one year + PasswordLastSet , we are using this as our AD prevents us from querying for Password expired info. and as a rule all our passwords are set to expire one year from the time they were last set. So to get PasswdExp we are adding one year to PasswordLastSet

    I have tried to run your modified code but I am getting the error  at line 13 of the code as shown below,  Attached is the code as an attachment, please note I have commented the email stub portion of the code  for now as I am only focussing on generating an output file for now.

    Get-ADUser : Error parsing query: '{ Enabled -eq $True -and PasswordLastSet -gt 0 }' Error Message: 'syntax error' at position: '1'.
    At C:UsersDesktopPower_Shell_Script_For Expired_accountstst_op.ps1:13 char:10
    + $users = Get-ADUser @GetADParams |
    +          ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDi
    rectory.Management.Commands.GetADUser

    Line 13 of the code is

    $users = Get-ADUser @GetADParams |
    Select-Object -Property 'Name', 'PwdLastSet' |
    sort-object -property 'PwdLastSet'
    0
  • Hello David,

    Thanks for your suggestions, I have tried to use this code as shown below to output the message to a file based on the number of days to expiry of the password, but somehow I think I am still missing something, I dont see any output getting generated. Where could I be going wrong ? Thanks for your help.

    IQ

    --------------------------------------------------------

    $SevenWarnDate = (get-date).adddays(7).ToLongDateString()
    $OneDayWarnDate = (get-date).adddays(1).ToLongDateString()
    
    #Find accounts that are enabled and have expiring passwords
    
    $users = Get-ADUser -filter {Enabled -eq $True -and PasswordLastSet -gt 0 } `
    -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=cit,DC=cc" `
    -Properties "Name", PasswordLastSet | Select-Object -Property "Name", "PasswordLastSet" |`
    sort-object -property PasswordLastSet
    $PasswordExp = $users.PasswordLastSet.Addyears(1)
    $MailParams = @{
    To = $users.name
    From = 'iq@mail.cit.cc'
    SMTPServer = 'mail.cit.cc' #$SMTPServer
    Subject = 'Test' #$Subject
    }
    switch ($PasswordExp)
    {
    ($PasswordExp -eq $OneDayWarnDate) {
    $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $SevenDayWarnDate, $EmailStub4 -join ' ')))
    $file = get-content test.txt -Raw
    $file = get-content test.txt
    set-content -Path test.txt -value $file
    get-content test.txt
    break
    }
    ($PasswordExp -eq $SevenWarnDate) {
    $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $ThreeDayWarnDate, $EmailStub4 -join ' ')))
    $file = get-content test.txt -Raw
    $file = get-content test.txt
    set-content -Path test.txt -value $file
    get-content test.txt
    break
    break
    }
    ($PasswordExp -eq $FifteenDayWarnDate) {
    $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' ')))
    $file = get-content test.txt -Raw
    $file = get-content test.txt
    set-content -Path test.txt -value $file
    get-content test.txt
    break
    }
    ($PasswordExp -eq $ThirtyDayWarnDate) {
    $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' ')))
    $file = get-content test.txt -Raw
    $file = get-content test.txt
    set-content -Path test.txt -value $file
    get-content test.txt
    break
    }
    }
    0
  • I have tried using   Set-Content -Path C:test.txt -Value 'foo'   to write the output to a file basically I need the UserId, PasswordExp written to the test file.  This did not work,  Is there a different command to be used to write to a file ?

    Please let me know.

     

    Thanks

    IQ

     

    0
  • Hello,

    I am trying to modify the following PowerShell code to write to a file within the foreach loop's if statement. So instead of  Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject `
    -Body $EmailBody

    I would like to write to a file, later this file will be emailed to the Domain Admins.

    Please let me know how I can output the Send Mail message line of code into a file .

    #Import AD Module
    Import-Module ActiveDirectory
    
    #Create warning dates for future password expiration
    $ThirtyDayWarnDate = (get-date).adddays(30).ToLongDateString()
    $FifteenDayWarnDate = (get-date).adddays(15).ToLongDateString()
    $SevenWarnDate = (get-date).adddays(7).ToLongDateString()
    $OneDayWarnDate = (get-date).adddays(1).ToLongDateString()
    
    #Find accounts that are enabled and have expiring passwords
    
    $users = Get-ADUser -filter {Enabled -eq $True -and PasswordLastSet -gt 0 } `
    -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=ed,DC=cn" `
    -Properties "Name", PasswordLastSet | Select-Object -Property "Name", "PasswordLastSet" |`
    sort-object -property PasswordLastSet
    $PasswordExp = $users.PasswordLastSet.Addyears(1)
    
    foreach ($user in $users) {
    if ($PasswordExp -eq $OneDayWarnDate) {
    $days = 1
    $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $SevenDayWarnDate, $EmailStub4 -join ' '
    
    Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody
    }
    elseif ($PasswordExp -eq $SevenWarnDate) {
    $days = 7
    $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $ThreeDayWarnDate, $EmailStub4 -join ' '
    
    Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject `
    -Body $EmailBody
    }
    elseif ($PasswordExp -eq $FifteenDayWarnDate) {
    $days = 15
    $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' '
    
    Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody
    }
    elseif ($PasswordExp -eq $ThirtyDayWarnDate) {
    $days = 30
    $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' '
    
    Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody
    }
    else {}
    }
    0
  • Hi Leos,

    We are having some trouble connecting to our mail server, so we would like to first develop this pseudo code and later integrate it with email server

    Get Service_Account_List Order by PasswordExpireDate Decending
    Loop Service_Account in Service_Account List
    Is Expire_Date < 1 ?
    Message := Service_Account + "Account Password Expired"**
    Else Is Expire_Date <= 7?**
    Message := Service_Account + "Account Password Will Expire within in 7 Days"**
    Else Is Expire_Date <= 15?**
    Message := Service_Account + "Account Password Will Expire within in 15 Days"**
    Else Is Expire_Date <= 30?**
    Message := Service_Account + "Account Password Will Expire within in 30 Days"
    End Is
    
    Store Message in file
    End Loop

    What is the best way to do this basically put all Accounts with the criteria given in a file and then loop through that file ?

    0
  • Thanks everyone for your suggestions.  Looks like the requirements are changed for what we are trying to do here. I value your suggestions and your time to reply back.

    Let me post what we are trying to do again

    I am using the following script to get a list of all AD users

    Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
    Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}| Export-CSV -Path ADUsers.csv

    Using the users in the ADUSer.csv file (which is obtained  using above code) , we would like to use the following pseudo code,

    Get Service_Account_List Order by PasswordExpireDate Decending
    Loop Service_Account in Service_Account List
    Is Expire_Date < 1 ?
    Message := Service_Account + "Account Password Expired"**
    Else Is Expire_Date <= 7?**
    Message := Service_Account + "Account Password Will Expire within in 7 Days"**
    Else Is Expire_Date <= 15?**
    Message := Service_Account + "Account Password Will Expire within in 15 Days"**
    Else Is Expire_Date <= 30?**
    Message := Service_Account + "Account Password Will Expire within in 30 Days"
    End Is
    
    Store Message in file
    End Loop

    Needed some help is building this pesudo code shown above, I am also going through tutorials and material which helps me translate this pesudo code into real code  but since Powershell scripting is new to me, I am finding it a bit diificult. Any help will be highly appreciated.

    0
  • Hi,

    I am using the following Get-ADUser cmdlet to retrieve the list of all AD users and output these to a file but this list is retrieving only 5 or 6 users, even though the number of active AD users is around 10,000. Where could I be going wrong ? Please advise.

    Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } `
    -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=city,DC=aa" `
    -Properties Name, msDS-UserPasswordExpiryTimeComputed | Select-Object `
    -Property Name, @{Name="PasswordExpiry";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} |`
    sort-object -property PasswordExpiry | `
    Export-Csv -Path ./Password_Expiration.csv -NoType
    0
  • Tried the script suggested in the post but I am getting an error

    Get-ADUser : The search filter cannot be recognized
    At line:21 char:1
    + Get-ADUser -LDAPFilter $LDAP | ForEach-Object {
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

    0
  • thanks for your suggestions, will try this code to make it work on Windows 2016/Windows 10.  For now I am just trying to write the soon to be expiring accounts in a file and then use SMTP to send an email, this needs to be automated using a Powershell script. Will let u know how it goes, thanks for your suggestion.

    0
  • Hello,

    I would like to use a pseudo code to as shown below, to create a file and then use this file to set up a script which automatically emails domain admins when a password is set to expire. Can someone please send me the exact code , I have tried some options in Windows Powershell ISE but not sure how to make a start. Any help will be appreciated.

    Get Service_Account_List Order by PasswordExpireDate Decending
    Loop Service_Account in Service_Account List
    Is Expire_Date < 1 ?
    Message := Service_Account + "Account Password Expired"**
    Else Is Expire_Date <= 7?**
    Message := Service_Account + "Account Password Will Expire within in 7 Days"**
    Else Is Expire_Date <= 15?**
    Message := Service_Account + "Account Password Will Expire within in 15 Days"**
    Else Is Expire_Date <= 30?**
    Message := Service_Account + "Account Password Will Expire within in 30 Days"
    End Is
    
    Store Message in file
    End Loop
    0
  • IQ's profile was updated 2 weeks, 5 days ago

    1+
    avatar
  • Send an email alert as the password expiry date is approaching for enabled service accounts. For example, maybe an alert would be sent 30 days before, then 15 days, then 7 days then 1 day. Ideally, the alerts would be sent to the service account owner, and the final alert can be copied to the domain admins.

    Can someone please provide us a script which does this ?

    0
  • IQ posted a new activity comment 2 weeks, 5 days ago

    I am looking at a script which does the following:
    Send an email alert as the password expiry date is approaching for enabled service accounts. For example, maybe an alert would be sent 30 days before, then 15 days, then 7 days then 1 day. Ideally, the alerts would be sent to the service account owner, and the final alert can be copied to the domain admins.

    Elaborate on the rationale for this request and possible positive effects on the business.
    Service accounts have been recently reconfigured to comply with organization's access control policies, whereby passwords expire after 365 days. When the password expires, any service utilizing the affected account will immediately fail. To avoid the potential downtime, a reminder to change the password in advance would prevent an unexpected password expiry.

    0
  • IQ posted an update in the group Group logo of PowerShellPowerShell 2 weeks, 5 days ago

    I am a new user to PowerShell, would like to know how to automate a script where in we are trying to retrieve expired passwords and email the system account holder.

    0
    • I am looking at a script which does the following:
      Send an email alert as the password expiry date is approaching for enabled service accounts. For example, maybe an alert would be sent 30 days before, then 15 days, then 7 days then 1 day. Ideally, the alerts would be sent to the service account owner, and the final alert can be copied to the domain admins.

      Elaborate on the rationale for this request and possible positive effects on the business.
      Service accounts have been recently reconfigured to comply with organization’s access control policies, whereby passwords expire after 365 days. When the password expires, any service utilizing the affected account will immediately fail. To avoid the potential downtime, a reminder to change the password in advance would prevent an unexpected password expiry.

      0
  • IQ became a registered member 2 weeks, 5 days ago

    1+
    avatar