get users not in group and exclude some samaccountnames from output.

Welcome Forums General PowerShell Q&A get users not in group and exclude some samaccountnames from output.

Viewing 1 reply thread
  • Author
    Posts
    • #207696
      Participant
      Topics: 2
      Replies: 2
      Points: 32
      Rank: Member

      Hi,

      looking to get this working somehow.  I have a script that exports users that are not in a group to a csv file.  I need to not export some users to the csv file.  how can I adjust this.  below is one of my failing scripts. 🙁     Thanks in advance for any assistance.

      import-module activedirectory
      $valuesSamAcctName = @(
      ‘train14’
      ‘train15’
      ‘train2’
      ‘train7’)
      # above, more will be added in future to exclude in output
      $File = “C:\TaskScripts\FPPG-DOC\NotIn_FPPG-DOC_TEST_a1.csv”
      $mySearchBase = “OU=test,DC=domain,DC=com”
      $myG = (Get-ADGroup “myGroup”).distinguishedname
      Get-ADUser -SearchBase $mySearchBase -Filter { -not (memberof -eq $myG) }`
      -Properties samaccountname, enabled, cannotchangepassword, PasswordNeverExpires |
      where {($_.CannotChangePassword -eq $False) -and ($_.enabled -eq $True)`
      -and ($_.samaccountname -ne $valuesSamAcctName.ToString()) } |
      select samaccountname,enabled, PasswordNeverExpires, cannotchangepassword |
      sort samaccountname |
      Export-Csv $File -NoTypeInformation

       

       

       

    • #207711
      Participant
      Topics: 12
      Replies: 1622
      Points: 2,560
      Helping Hand
      Rank: Community Hero

      Please use the PRE tags when posting code. Move the enabled and cannotchangepassword into the filter so that you not returning those records from the intial AD query. The valuesSamAcctName is an array, so you should use the -contains or -notcontains operator to filter the user:

      import-module activedirectory
      
      $valuesSamAcctName = @(
          ‘train14’
          ‘train15’
          ‘train2’
          ‘train7’
      )
      
      # above, more will be added in future to exclude in output
      $File = “C:\TaskScripts\FPPG-DOC\NotIn_FPPG-DOC_TEST_a1.csv”
      $mySearchBase = “OU=test,DC=domain,DC=com”
      $myG = (Get-ADGroup “myGroup”).distinguishedname
      
      $users = Get-ADUser  -SearchBase $mySearchBase -Filter {(CannotChangePassword -eq $false) -and (Enabled -eq $true) -and (MemberOf -notlike $myG)} -Properties samaccountname, enabled, cannotchangepassword, PasswordNeverExpires |
               Where {$valuesSamAcctName -notcontains $_.SamAccountName} |
               Select samaccountname, enabled, PasswordNeverExpires, cannotchangepassword |
               sort samaccountname
      
      $users | Export-Csv $File -NoTypeInformation
      
Viewing 1 reply thread
  • You must be logged in to reply to this topic.