Been a while since I posted, but i've hit a road-block which an annoying issue
I have a need to scan all of the companies domains for user accounts based on full name, as is FIRST LAST
The same code works fine when running a get-aduser -identity -server domain.name, but using
Get-aduser -filter -server doesn't work inside a For loop, and I'm not sure why!
Here's the code:
$AllDomains = (Get-ADForest).domains
Function Check-ADUser {
Param(
$FullName,
$ADList
)
$ADUserArray = @()
ForEach ($SubDomain in $ADList) {
write-host "Checking for $FullName on $SubDomain ..."
$UserADDomain = Get-ADUser -Server $SubDomain -Filter {(Name -eq $Fullname)} -properties * -ErrorAction SilentlyContinue | Select @{n="DomainName"; e={($_.CanonicalName -split '/')[0]}} `
| Select-Object DomainName -ExpandProperty DomainName
} #ForEach $Domain
The results return black
Here's the code that work fine:
$AllDomains = (Get-ADForest).domains
Function Check-ADUser {
Param(
$FullName,
$ADList
)
$ADUserArray = @()
ForEach ($SubDomain in $ADList) {
write-host "Checking for $FullName on $SubDomain ..."
$UserADDomain = Get-ADUser -Server $SubDomain -Identity $userName -properties * -ErrorAction SilentlyContinue | Select @{n="DomainName"; e={($_.CanonicalName -split '/')[0]}} `
| Select-Object DomainName -ExpandProperty DomainName
} #ForEach $Domain
The function is called via a for loop against each user as such
$Users = @"
Rocky Balboa
Bruce Willis
Gene Simmons
Liz Phair
Steven Segal
"@ | ForEach {$_.Split([String[]]"`r`n",[StringSplitOPtions]::None)}
$outarray = @()
ForEach ($user in $Users) {
$aa = Check-ADUser -FullName $User -ADList $AllDomains
}
The only real difference in the code within the function, is the use the -filter instead of -identity on the get-aduser cmdlet
What's odd, is that if I run the code outside of the for loop, it works! I'm thinking it's a Powershell gotcha! any help appreciated :-)
Owen
{ ... }) as-Filterarguments. - mklement0$FullName, because you don't use that in the second example. Trying to identify a user by the Name property is asking for trouble. Better filter onSamAccountName,EmailAddress,UserPrincipalName,DistinguishedNameor evenSID, because these properties are/should be unique within the domain. As aside, it is bad practice to useProperties *. This pulls out ALL properties, where in your code you don't even need any user properties at all, except the one you are filtering on plus theCanonicalName- Theo