Getting Windows domain username in correct case (to match Active Directory)

How can I get a Windows 7 domain user's username in the case that it is stored in Active Directory (such as RoseRoss), rather than whichever case they happened to type it when logging in to their workstation (such as roseross or rOsErOSs or whatever)?

Is there a setting which will force the %USERNAME% environment variable always to use the canonical Active-Directory case?

For some users in this office, %USERNAME% is always in the case they type it when logging in.

For other users, %USERNAME has until recently always been in the canonical case (for a user logging in as elenasimpson it returns ElenaSimpson), but last week mysteriously started only doing this sometimes and the rest of the time returning it as typed. Rebooting often toggles to the other behaviour.

So I'd like either a way of forcing the canonical-case behaviour on %USERNAME% all the time, or to be able to ignore that environment variable and find an alternative way of getting the username that is in the canonical Active-Directory case.

Thanks.


This answer falls into your 2nd option of querying the username from AD. If you're open to a powershell solution you have a few options.

Your situation feels like you want to do this from each users workstation, and PS AD Module may not always be available across those targets. In that case you can get the same info like this:

([adsi]"WinNT://$env:userdomain/$env:username,user").name
RoseRoss

If the AD module is available you could do this.

(get-aduser -id $env:username).samAccountName
RoseRoss