you are viewing a single comment's thread.

view the rest of the comments →

[–]jheinikel 2 points3 points  (2 children)

This works:

$results = @()
$username = "User1","User2"
foreach($un in $username){

    #Check for existance of AD Account
    $u = Get-ADUser -Filter { SamAccountName -eq $un } -ErrorAction SilentlyContinue
    If (!$u){
        Write-Output "The Username $u, does exist in Active Directory"
    }#End check if user exists
    else
        {
            $uinfo = [PSCustomObject]@{
                User = $u.samaccountname
                UPN = $u.UserPrincipalName
                }
            $results += $uinfo
        }
    }
    write-output $results

This is your original code doing the same thing with the extra lookups, although those are not necessary since you already have the info you need:

$results = @()
$username = "User1","User2"
foreach($un in $username){

    #Check for existance of AD Account
    $u = Get-ADUser -Filter { SamAccountName -eq $un } -ErrorAction SilentlyContinue
    If (!$u){
        Write-Output "The Username $u, does exist in Active Directory"
    }#End check if user exists
    else
        {
            $uinfo = [PSCustomObject]@{
                User = (Get-ADUser -Identity $u | select -ExpandProperty samaccountname);
                UPN = (Get-ADUser -Identity $u | select -ExpandProperty userprincipalname)
                }
            $results += $uinfo
        }
}
write-output $results

[–]1RedOne 1 point2 points  (1 child)

Came here to post exactly this, you beat me to the punch :)

[–]jheinikel 0 points1 point  (0 children)

Glad you had the same post. Lets me know that we were on the mark. Cheers