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

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. :frowning: 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

 

 

 

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