Im a Linux Sys Admin by profession, but am having to do some powershelling. My problem is this:
Im getting a list of active users from the AD with this command:
$allusers= get-aduser -Filter {Enabled -eq $true} | FT samAccountName
My intent being that $allusers becomes an array filled with the lines of output from the get-aduser command. popping this block just after the array is populated seems to confirm that is indeed the case.
for ($i; $i -le $allusers.length; $i++) {
$allusers[$i]
}
Great! so now I want to check if a given username exists within that array. I see that arrays include a very handy "Contains()" function, which looks like it should serve my purpose.
echo $allusers.Contains("joeq")
But alas! I get this error:
Method invocation failed because [System.Object[]] doesn't contain a method named 'contains'.
At C:\Users\dylanh\jirauserpurge.ps1:33 char:24 + echo $allusers.contains <<<< ("joeq") + CategoryInfo : InvalidOperation: (contains:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
Hmmm... OK, lets go "old skool"
for ($i; $i -le $allusers.length; $i++) {
if ($allusers[$i] -eq "joeq") {
echo "joeq present"
}
}
The condition is never matched! My brain hurts! OK, Its possible there's some whitespace characters causing mischief here, lets trim:
for ($i; $i -le $allusers.length; $i++) {
if ($allusers[$i].Trim() -eq "joeq") {
echo "joeq present"
}
}
But no, that results in this:
Method invocation failed because [Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData] doesn't contain a method named 'Trim'.
At C:\Users\dylanh\jirauserpurge.ps1:39 char:24
+ if ($allusers[$i].Trim <<<< () -eq "nickf") {
+ CategoryInfo : InvalidOperation: (Trim:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Clearly its some kind of type casting problem that I'm missing. What do I need to do to allow searching the "array" for a specific value?
UPDATE: With the help of fdibot's answer and HopelessN00b's comment, I have a working solution:
$allusers= get-aduser -Filter {Enabled -eq $true}
$usernames = @()
for ($i=0; $i -le $allusers.length; $i++) {
$usernames += $allusers[$i].SamAccountName
}
$usernames -contains "joeq"
The additional for loop seems a bit redundant TBH (or at least it would be in bash!) Ah well! thanks for your input everyone.