0

I want to exclude some users inside AD.

e.g

TST292736ca
PRD1212ca
PRD212132121ca
PRD293873
PRD122
TST141444
TST122
cyberhw12

and so on

My question is : I want to exclude "Users starting with TST and ending with ca" , "Users starting with PRD and ending with ca" , "starting with cyber" users.

script :

get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
Arbelac
  • 1,698
  • 6
  • 37
  • 90

3 Answers3

0

I would do it something like that: fill $ADUsersExcluded with excluded users and with foreach and if fill new array with users $filteredUsers.

[array]$ADUsersExcluded = $null
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "TST*ca"}
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "PRD*ca"}
$ADUsersExcluded += Get-ADUser -Filter {SamAccountName -like "cyber*"}

$AllUsers = Get-ADUser -Filter * -Properties Name,PasswordNeverExpires,PasswordExpired,PasswordLastSet,EmailAddress | Where-Object {$_.Enabled -eq "True"} | Where-Object { $_.PasswordNeverExpires -eq $false } | Where-Object { $_.passwordexpired -eq $false }
[array]$filtered = $null
foreach($user in $AllUsers) {
    if($ADUsersExcluded -notcontains $user){
        $filteredUsers += $user
    }
}
$filteredUsers
Alex R.
  • 467
  • 3
  • 14
  • 1
    `[array]$filtered = $null` should probably be `[array]$filteredUser = @()` (incorrect name and not `$Null`). Besides, [try to avoid using the increase assignment operator (`+=`) to create a collection](https://stackoverflow.com/a/60708579/1701026) as it might get very expensive. – iRon Jul 08 '22 at 11:51
0

First, dont forget to import AD module. Check condition values.

[array] $ADExcludedUser = 'User1', 'User2', 'User3'

$AllUsers = Get-ADUser -Filter * -Properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress | Where-Object { ( $_.Enabled -eq "True" ) -and ( $_.PasswordNeverExpires -eq $false ) -and ( $_.name -notin $ADExcludedUser ) }
$AllUsersExceptExcluded = $AllUsers | where-object { $_.name -notin $ADExcludedUser }

write-host -object $AllUsersExceptExcluded
0

I would use a regex -notmatch for this:

Get-ADUser -Filter "Enabled -eq $true" -Properties PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |
Where-Object { $_.PasswordNeverExpires -eq $false -and $_.PasswordExpired -eq $false -and  $_.Name -notmatch '^(TST|PRD).*ca$|^cyber' } 

If you need case-sensitivity, change notmatch into -cnotmatch

Theo
  • 57,719
  • 8
  • 24
  • 41