Hi,

I have written a simple PS script which will pull user data such as samaccountname and emailaddress using first and last names pulled from a CSV file. The script is below:

Import-Module ActiveDirectory

$users = Import-CSV “locationofcsvfile”

foreach ($user in $users) {

$gname = $user.givenname
$sname = $user.surname

get-aduser -filter {givenname -eq $gname -and surname -eq $sname} -properties * | select samaccountname,emailaddress
}

The following errors appear when running the script:

Please tell me what I am missing…

Thanks!

1 Spice up

What is the structure of your CSV file? Does its first row have titles? Can you post a small example - sanitized of course.

1 Spice up

If you post code, please use the ‘Insert Code’ button. Please and thank you!

codebutton_small.png

try like so, but as said, it depends on your CSV file.

Import-Module ActiveDirectory

$users = Import-CSV "c:\location\of\file.csv"

foreach ($user in $users) {

    $gname = $user.givenname
    $sname = $user.surname

    if ($gname -and $sname) {
        get-aduser -filter "givenname -eq '$gname' -and surname -eq '$sname'" -properties * | 
            select samaccountname, emailaddress
    }
    else {
        Write-Warning "no name info"
    }
}

csv.png

CSV should have a header like givename,surname based on your code you running. Looks you have gname and sname so it will be

Import-Module ActiveDirectory

$users = Import-CSV "c:\location\of\file.csv"
foreach ($user in $users) {

    $gname = $user.gname
    $sname = $user.sname
      $user=Get-ADUser -Filter "GivenName -eq '$gname' -and Surname -like '$sname'"  -properties Emailaddress
       if( $User )
    {
        $user |select samaccountname, emailaddress
    }
    else
    {
    New-Object PSObject -Property @{
            GivenName  = $Gname
            Surname    = $sname
            Status     = 'MISSING ACCOUNT'
            }
    }

}
4 Spice ups

JitenSh,

Thanks.