Home > Mobile >  Get-ADuser multiple exclude users
Get-ADuser multiple exclude users

Time:07-09

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 }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related