How to get the user's displayName when using PowerShell 2.0 and the Active Directory module is not present?

I’ve tried all kinds of things to get the user’s displayName from AD inside of PowerShell 2.0 but can’t seem to find something that works. The majority of computers will not have the Active Directory module installed and there are still some PowerShell versions below 5.1 with the lowest still present being 2.0.

I’ve tried

$adsysinfo = New-Object -ComObject "ADSystemInfo"
$adsysinfo.GetType().InvokeMember("$($env:USERNAME)",$Null,$adsysinfo,$null)

Which gives me

+ $adsysinfo.GetType().InvokeMember <<<< ("$($env:USERNAME)",$Null,$adsysinfo,$null)
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Also tried

$Searcher = New-Object DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = 'LDAP://DC=DOMAIN,DC=DOMAIN'
$Searcher.Filter = '(&(objectCategory=person))'
$Searcher.FindAll("$env:USERNAME") 
#Note: I also tried
$Searcher.FindOne("$env:USERNAME")

Which gives me

Cannot find an overload for "FindAll" and the argument count: "1".
At line:1 char:18
+ $Searcher.FindAll <<<< ("$env:USERNAME")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
#AND
Cannot find an overload for "FindOne" and the argument count: "1".
At line:1 char:18
+ $Searcher.FindOne <<<< ("$env:USERNAME")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Any suggestions on how I can get the AD user’s displayName in this environment?

I also had to support PowerShell 2 (dont laugh). I reverted back to good old ADSI.

$System = 'DCHostName'
$AcctName = $ENV:UserName
$userInfo = ([ADSI]"WinNT://$System/$AcctName),user")

Then of course to get the properties …

$userInfo | Get-Member

I believe the FullName property will get you what you need?

Personally, I check the powershell version first and only use ADSI if the version is 3 or less. ADSI caon also be use on the local system, you just define the $System variable.

@tonyd Thanks, that didn’t work for me, but you did point me in the right direction. This one liner is what worked for me:

([ADSI]"WinNT://DOMAIN/$($env:USERNAME)")

And the useless fact of the day, ADSI works all the way back to Windows NT :slight_smile:

Fortunately, we don’t have any of those left!