Search code examples
powershellscheduled-taskschange-password

PowerShell script Scheduled Task change local user password value based on set password


I am working on a PowerShell script that would run in a Task Scheduler. The way I want it to work is:

Default value is set to force user to change password at next logon: net user su /logonpasswordchg:yes user must change password at next logon

Now the code would be something like:

$password = Azerty123! if $password is different from $password switch password from "user must change password at next logon" to "Password never expires" else leave value to change password at next logon

After multiple tests I figured that the 2 following values would need to be switched based on the current password

  1. Set-LocalUser -Name "su" -PasswordNeverExpires:$true
  2. Set-LocalUser -Name "su" -PasswordNeverExpires:$false
  3. net user su /logonpasswordchg:yes
  4. net user su /logonpasswordchg:no

Basically the script is deployed with Intune, creates a Task Scheduler, it would check the password value every day one per day, if the password has been changed, the password value is changed to never expire, as long as the password as never been changed, leave it as change password at next logon. Can anyone help me on this ? sorry for my clumsy explanations


Solution

  • Alternative approach could be to change the password expiry setting globally on Windows system. This will apply to all users and can be done prior specific user changed their password. It can be accomplished by running following command:

    net accounts /maxpwage:0
    

    Note: check comments section to the answer for in depth discussion of other approaches