简体   繁体   中英

get-ADUser with parameters in a foreach loop from csv with powershell

I try to lookup AD with powershell 3 and check if users (sAMAccountName) in my csv are existing and active in AD. However I am hopping from one error to the next one probably based on brackets and parenthesis but I do not find the correct way. I tried different filters, tried to pass them through a variable but I end up with "a parameter cannot be found that matches parameter name -eq...". It looks like the error is at Get-ADUser as $adsearch is not set therefore fails to evaluate if($adsearch).

the csv file is sanitized (leading spaces etc.) and looks like (only one column with SAMAccountName):

john.doe
jane.doe
doej2
foo.bar
barf5

param ($inputfile='.\users.csv',$logfile='.\log.csv')
$csv = Import-CSV $inputfile

#"samAccountName,Search Result" | Add-Content $logfile

ForEach ($user in $csv){
    echo $user;
    #$adsearch = Get-ADUser -Filter 'sAMAccountName -eq "$($user)" -and Enabled -eq $true'
    #$filter = "sAMAccountName -eq $($user) -and Enabled -eq $($true)"
    #Write-Host "Filter is $filter"
    $adsearch = Get-ADUser -Filter "(sAMAccountName -eq '$($user)') -and (Enabled -eq '$($true)')"
    echo $adsearch
    if ($adsearch){
        echo "Found";
        echo "$error"
        #"$user, Found" | Add-Content $logfile
        }
    else{
        echo "NOT FOUND";
        echo "$error"
        #"$user, Not Found" | Add-Content $logfile
        }
    }

Solved.

For reference I leave the buggy script above, here is the working script (thanks Tomer and Charlie Joynt):

param ($inputfile='.\users.csv',$logfile='.\log.csv')
$csv = Import-CSV $inputfile

"samAccountName,Search Result,Error" | Add-Content $logfile

ForEach ($user in $csv){
    $username = $user.SAMAccountName;
    $adsearch = Get-ADUser -Filter {(samAccountName -eq $username) -and (Enabled -eq $true)}
    echo "search for active user $user"
    if ($adsearch){
        echo "Found";
        "$user, Found" | Add-Content $logfile
        }
    else{
        echo "NOT FOUND";
        "$user, Not Found, $error" | Add-Content $logfile
        }
    }

For the CSV file you showed, when I add a header line SAMAccountName , the following works for me:

$username = $user.SAMAccountName
$adsearch = Get-AdUser -Filter {(samAccountName -eq $username) -and (Enabled -eq $true)}

Notice the curly brackets instead of the quote marks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM