Help with powershell script

Skip Hofmann 341 Reputation points
2021-11-05T16:06:37.337+00:00

Hello all

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 from the day the script is run
  4. if a match is not found write the non matched accounts to a separate .csv file

ISSUE
I cant get the differences between the import .csv file and what is found in the OU's written to the output file

$OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=test-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=test-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
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,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,091 Reputation points
    2021-11-07T19:39:06.463+00:00

    Try this one:

    $OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=test-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=test-tech,DC=com"
    # Load hash with UPNs
    $UPNs = @{}
    $OUNames |
        ForEach-Object{
            Get-ADUser -Filter * -SearchBase $_ -SearchScope OneLevel |
                ForEach-Object{
                    $UPNs[$_.UserPrincipalName] = $false
                }
        }
    Import-Csv C:\temp\test2.csv |
        ForEach-Object {
            $u = get-aduser -Filter "userPrincipalName -eq '$($_.upn)'"
            if ($u) {
                        Set-ADAccountExpiration -Identity $u.distinguishedName -TimeSpan 90.0:0
                        $UPNs.($_.UPN) = $true
            }  else {
                [PSCustomObject]@{
                    UPN = $_.UPN
                    Reason = "UPN not found in AD"
                }
            }
        } | Export-CSV C:Temp\NotInAD.csv -NoTypeInformation
    $UPNs.GetEnumerator()|
        ForEach-Object{
            if (-not $_.Value){
                [PSCustomObject]@{
                    UPN = $_.Key
                    Reason = "UPN not in CSV, or UPN in different OU"
                }
            }
        } | Export-Csv C:\Temp\NotInCSV.csv -NoTypeInformation
    

5 additional answers

Sort by: Most helpful
  1. MotoX80 31,826 Reputation points
    2021-11-07T16:12:00.56+00:00

    If get-aduser works, then $FoundUser will be incremented by one.
    If get-aduser fails, then $UnknowUser will be incremented by one.

    $FoundUser + $UnknowUser will equal the total number of rows in the csv.

    If $OUNames -contains $OU, then $GotOne will be incremented by one. (Assuming that you corrected my typo error )
    If the OU test fails, then $NotInOU will be incremented by one.

    $Gotone + $NotinOU will equal $FoundUser.

    If $NotInOU is greater than one, or $UnknowUser is greater than one, then the current object (dollar underscore) will be added to the $WhoAreThesePeople array.

    If your csv only has one row in it, does $FoundUser equal one? If not, go figure out what is wrong as to why it's not finding the user.

    Once get-aduser works, does $NotInOU equal 1? If it does, analyze the OU names to figure out why it's not working. Does $OU.gettype() show that it is a string? Does $OU.length match the number of characters that visually display on the screen?

    Here is an updated script with more diagnostics. Please post the entire output of this.

    Be advised that I don't have a good way to test this. It may contain mistakes.

      $WhoAreThesePeople = @() 
      $FoundUser = 0
      $GotOne = 0
      $NotInOU = 0  
      $UnknowUser = 0 
      $OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=test-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=test-tech,DC=com"
       Import-Csv C:\temp\test2.csv |
           ForEach-Object {
                $u = get-aduser -Filter "userPrincipalName -eq '$($_.upn)'"
                if ($u) {
                     $FoundUser++
                     $OU = $u.DistinguishedName.Substring($u.DistinguishedName.IndexOf('OU=',[System.StringComparison]::CurrentCultureIgnoreCase))
                     if ($OUNames -contains $OU) {
                         $GotOne++                                    # fixed per Rich 
                         Set-ADAccountExpiration -Identity $u.distinguishedName -TimeSpan 90.0:0
                     } else {
                         $NotInOU++
                         $WhoAreThesePeople+= $_
                         "A user was added to WhoAreThesePeople because we did not find the OU."
                         "The OU we tested is {0}" -f $OU
                         "The OU variable type is {0} " -f $OU.gettype().Name
                         "The string length is {0}" -f $OU.length                    
                         "Current WhoAreThesePeoplecount is {0}" -f $WhoAreThesePeople.count 
                     }
                }  else {
                     $UnknowUser++ 
                     $WhoAreThesePeople+= $_ 
                     "An unknown user was added to WhoAreThesePeople. Current count is {0}" -f $WhoAreThesePeople.count 
                }
           } 
      "We found {0} users." -f $FoundUser 
      "Of the users that we found, {0} were NOT in the OU." -f $NotInOU   
      "Expiration was set on {0} users." -f $GotOne
      "Count of users NOT found in AD: {0}" -f $UnknowUser  
      "Total WhoAreThesePeople count is {0}" -f $WhoAreThesePeople.count 
      $WhoAreThesePeople | Export-Csv C:\temp\WhoAreThesePeople.csv -NoTypeInformation