help with Poweshell compare\hashtable

Skip Hofmann 341 Reputation points
2021-11-03T23:41:29.73+00:00

Hello. Looking for help with constructing a PowerShell script that will do the following

  1. csv file contains list of users (upn)
  2. PowerShell script reads all users from csv file (step1.) does a compare or hash table against users in three specific OU's in AD using (upn). The three specific OU's contain all of our vendor accounts
  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

Thank you very much in advance for any help

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
5,848 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
{count} votes

Accepted answer
  1. Rich Matheisen 44,776 Reputation points
    2021-11-04T15:03:11.447+00:00

    Try something like this:

    $OUNames = "OU=1,OU=X,DC=domain,DC=tld", "OU=2,OU=Y,DC=domain,DC=tld", "OU=3,OU=X,DC=domain,DC=tld"
    Import-Csv C:\Junk\AllHands.csv |
        ForEach-Object{
            $u = Get-ADUser -Filter "userPrincipalName -eq '$($_.UPN)'" -Properties AccountExpires,distinguishedName
            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:\Junk\WhoAreThesePeople.csv -NoTypeInformation
    

    NOTE: I haven't run this code. You should try it first by adding the "-WhatIf" switch to the Set-ADAccountExpiration cmdlet until you're sure it does what you want!


1 additional answer

Sort by: Most helpful
  1. Skip Hofmann 341 Reputation points
    2021-11-04T15:10:46.003+00:00

    Thank you very much. I appreciate your help! I will test in our lab

    0 comments No comments