I’ve been tasked with setting all users in our AD that are contractors to have their accounts expire at the end of our phiscal year. This sounds like a relatively easy task, but it’s been giving me issues.
All of our contractor accounts start with "c_" making them easy to find with
Get-ADUser -Filter * -Properties SAMAccountName | Where {$_.SAMAccountName -like "c_*"} | Select SAMAccountName | Export-Csv -LiteralPath C:\Results\AllContractors.csv -NoTypeInformation
Then it should just be a matter of adapting the command
Set-ADAccountExpiration -Identity "SAMAccountName" -DateTime "07/01/2023"
to be repeated for every SAMAccountName I have in the .csv.
All together I get this:
Get-ADUser -Filter * -Properties SAMAccountName | Where {$_.SAMAccountName -like "c_*"} | Select SAMAccountName | Export-Csv -LiteralPath C:\Results\AllContractors.csv -NoTypeInformation
$Users = Import-Csv -LiteralPath C:\Results\AllContractors.csv
ForEach($User in $Users){
Set-ADAccountExpiration -Identity $User -DateTime "07/01/2023"
}
But it keeps returning an error:
Set-ADAccountExpiration : Object reference not set to an instance of an object.
At line:4 char:5
+ Set-ADAccountExpiration -Identity $User -DateTime "07/01/2023"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Microsoft.Activ...ement.ADAccount:ADAccount) [Set-ADAccountExpiration], NullReferenceException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.NullReferenceException,Microsoft.ActiveDirectory.Management.Commands.SetADAccountExpiration
Any insight into this would be appreciated!
>Solution :
Your issue most likely is because you’re passing a PSCustomObject ($user) with a property named SamAccountName and Set-ADAccountExpiration does not know how to interpret it as its expecting the property value ($user.SamAccountName). Also you can definitely do all of this in a single pipeline using -PassThru. No need to export and then import back the CSV:
Get-ADUser -Filter "samAccountName -like 'c_*'" |
Set-ADAccountExpiration -DateTime '07/01/2023' -PassThru |
Select-Object SamAccountName |
Export-Csv -LiteralPath C:\Results\AllContractors.csv -NoTypeInformation