Help with script

Frequent Contributor

Hello all

This is what i am trying to accomplish. 

1. csv file contains a list of users UPN (header in csv = upn)

2. script reads all users from csv import file (step1.) does a compare or hash table against users in three specific OU's in AD using (upn).

3. If a match is found, extend account expiration + 90 days 

4. if a match is not found write the non matched accounts to a separate .csv file

*ISSUES*

1. When i run the script in my lab is its setting the expiration date per below . The expiration date was set for 11/14/2021, and when i ran  the script it set it as what you can see in the screen shot

 

date.GIF

 

2. The difference between what is in the import .csv file and what is in the OU's is not getting written to the .csv output file

 

 $OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=ip-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=ip-tech,DC=com"
 Import-Csv C:\temp\test2.csv |
     ForEach-Object{
          $u = get-aduser -Filter "userPrincipalName -eq '$($_.upn)'"
             if ($u){
             $OU = $u.DistinguishedName.Substring($u.DistinguishedName.IndexOf('OU=',[System.StringComparison]::CurrentCultureIgnoreCase))
             if ($OUNames -contains $OU){
                 Set-ADAccountExpiration -Identity $u.distinguishedName -DateTime ([datetime]::fromfiletime($u.accountexpires)).AddDays(90)
             }
             else{
                 $_
             }
         }
         else {
             $_
         }
     } | Export-Csv C:\temp\WhoAreThesePeople.csv -NoTypeInformation

 

Any help is greatly appreciated

 

1 Reply

@Skipster311-1 

I have the expiration issue resolved. This actually works for our needs 

"Set-ADAccountExpiration -Identity $u.distinguishedName -TimeSpan 90.0:0"

However im still struggling to get the differences written to the output file

 $OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=ip-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=ip-tech,DC=com"
 Import-Csv C:\temp\test2.csv |
     ForEach-Object{
          $u = get-aduser -Filter "userPrincipalName -eq '$($_.upn)'"
             if ($u){
             $OU = $u.DistinguishedName.Substring($u.DistinguishedName.IndexOf('OU=',[System.StringComparison]::CurrentCultureIgnoreCase))
             if ($OUNames -contains $OU){
                 Set-ADAccountExpiration -Identity $u.distinguishedName -TimeSpan 90.0:0
             }
             else{
                 $_
             }
         }
         else {
             $_
         }
     } | Export-Csv C:\temp\WhoAreThesePeople.csv -NoTypeInformation