Set-expirationdate delay


I use a script where a user is created , one of the settings is the expiration date.
When the line for the set-expirationdate is called, powershell throws a error, that the aduser can not be found.
I tried to workaround this, by pausing for 6 seconds to give AD the time to “think”
This is not working, only when I do a get-aduser $username (after all is done) the usewr is present in AD.
Then when I manually run the Set-expirationdate line, it is working fine. ( at that moment)

I am wondering why this is happening, and of course how I can fix this

# This will be the info needed to create the account
$ADM            = "adm-fu-"
$FirstName      = Read-Host "FirstName is?"
$MiddleInitial  = Read-Host "What are the Middle Initals?"
$LastName       = Read-Host "Lastname is?"
$Description    = Read-Host "Fill in the Ticketnr, and the function"
$FJDomain       = Read-host "what the e-mail domain, (like"
$Expiration     = Get-Date $((Get-Date).adddays(360)) -f 'yyyy-MM-dd'
$Emailaddress   = $FirstName + '.' +$LastName + $FJDomain
$Company        = Read-Host "What is the name of the Company"

$DefaultPassword= Read-Host "Create a strongpassword"

# setting the values for a adminaccount 
$Username = 'adm-fu-' + $lastname.substring(0,4) + $Firstname.substring(0,1)+'1'

#Create the New user Account
$NewUserParams = @{
'UserPrincipalName' = $Username
'Name' = $Username
'GivenName' = $FirstName
'Surname' = $LastName
'DisplayName' = $FirstName + $MiddleInitial + $LastName
'Description' = $Description
'EmailAddress'= $Emailaddress
'SamAccountName' = $Username
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force)
'CannotChangePassword' = $false
'Enabled'  = $True
'Initials' = $MiddleInitial
'Path' = "$OU,$Dn"
'Company' = $company
#'AccountExpirationDate' = Set-ADAccountExpiration -DateTime $Expiration

#Because of COVID and RDP, do not set " change at next logon" 
'ChangePasswordAtLogon' = $false

#Create the new user account
New-AdUser @NewUserParams

Sleep -Seconds 6

Set-ADAccountExpiration $username -DateTime $Expiration



Specify the same domain controller with the -Server parameter for both cmdlets. You’re probably hitting a different DC when you run Set-ADAccountExpiration and the new account hasn’t replicated.

Hello Matt,

Thank you for pointing the right direction.