4

I've been tasked with creating a script that reads in a file a list of Active Directory user IDs and then clears the flag for Password Never Expires. In addition, my security officer doesn't want the 500 users that have this setting to have their password immediately have to be reset, so he wanted the default Domain Policy of 90 days to be attributed at the time that the script is ran, so the user falls into the usual password rotation.

I've been trying to create a PowerShell script to do just that and am running into issues. Admittedly, I'm not the best at PowerShell so I'd appreciate some input.

I've got the flag to clear, but changing the PwdLastSet to -1 is proving to be tricky. I think it might be because I don't know how to read in a file and do two "ForEach-Object" commands from reading in a file. Could someone please look?

Import-CSV PasswordExpiry.csv | ForEach-Object {Set-ADUser -Identity $_.SamAccountName -PasswordNeverExpires:$false}

ForEach-Object {  
 $samaccountname = $_.SamAccountName  
  $today = Get-Date  

  $lastchange = [datetime]::FromFileTime($_.pwdlastset[0])  

  $timediff = New-TimeSpan $lastchange $(Get-Date)  

      $hoursdiff = $timediff.TotalHours  

  if ($hoursdiff -lt $hourschange_sincePwdChange) {  
    $todouser = Get-ADUser $samaccountname -Properties pwdLastSet  

    $todouser.pwdLastSet = 0  
    Set-ADUser -Instance $todouser  

    $todouser.pwdLastSet = -1  
    Set-ADUser -Instance $todouser  

          }  

}  

I get several positional parameter errors saying that it cannot accept the argument $null, but I'm not sure where I'm wrong.

3

AD will not let you change the date a password was last reset, except to 0 (which will force a password change at next login). To do that, you can't set the PwdLastSet manually, you have to use something like the following snippet:

Set-ADUser -Identity JoeBlow -ChangePasswordAtNextLogon $true
2

Give up, because you cannot (directly) modify the pwdLastSet attribute of a user. That attribute may only be set by the System (the Directory Services Engine) itself. (ERROR_DS_ATTRIBUTE_OWNED_BY_SAM)

See Microsoft doc MS-ADTS for more information.

1

I was able to accomplish this with the following:

Import-Module ActiveDirectory

$ADUserParams=@{ 
'Searchbase' = 'OU=Users,OU=Testing,OU=IT,OU=XXX,DC=XXX,DC=local' 
'Filter' = '*' 
'Properties' = 'cn','sn','givenname','displayName','mail','description','UserPrincipalName', 'employeeNumber', 'profilepath', 'title' 
}

$ADUsers = Get-ADUser @ADUserParams 
ForEach ($ADUser in $ADUsers) { 
    $ADUser = Get-ADUser $ADUser -properties pwdlastset 
    $ADUser.pwdlastset = 0 
    Set-ADUser -Instance $ADUser 
    $ADUser.pwdlastset = -1 
    Set-ADUser -instance $ADUser 
}

Taken from here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.