2

I've changed my username in Windows 10, and now I need to automate getting this changed username as a Powershell script But everything I try returns my old username apart from some AD-related query.

Example:

    $env:UserName

    whoami

    $(Get-WMIObject -class Win32_ComputerSystem | select username).username

Return my old username while my user was actually renamed.

Because of this I can't relatively get correct username to use in PS scripts.

Only thing that was able to extract it was this:

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

But on other machine it just returns empty result

mklement0
  • 245,023
  • 45
  • 419
  • 492
  • Have you changed your AD username? AD accounts and local accounts are different, so if you change the username of your domain account, the local username will remain the same. And the methods you have used first only can show your local username. – programmer365 Jun 08 '20 at 17:06
  • The powershell variable is based on your home foldername I believe. You cannot change the name of a user's folder afaik so it will stay like this unless you manually change it like `$env:username = "NewName"` – Nico Nekoru Jun 08 '20 at 17:28
  • @WasifHasan I don't have AD on my PC (AFAIK), it's not in domain or anything – RedSchuhart Jun 08 '20 at 18:22
  • How did you perform the rename? Was the user logged in during the rename and, if so, is your code being run in a login session created _after_ that happened? I'd suggest trying [`[Environment]::UserName`](https://docs.microsoft.com/dotnet/api/system.environment.username), which is [implemented](https://referencesource.microsoft.com/#mscorlib/system/environment.cs,1399) using the [`GetUserName()` Win32 function](https://docs.microsoft.com/windows/win32/api/winbase/nf-winbase-getusernamew), but it looks like that might have [the same problem](https://stackoverflow.com/q/58497564/150605). – Lance U. Matthews Jun 08 '20 at 19:29
  • @BACON I renamed my user using control panel. Yes, code is running after a restart. – RedSchuhart Jun 09 '20 at 08:10

1 Answers1

0

If you're trying to get the username used for signon, it should be ([adsi]"WinNT://$env:userdomain/$env:username,user").Name not .fullname.

EDIT: Environmental variables are not updated unless the application (Powershell in this case) is restarted. There are workarounds.

Rich Moss
  • 1,810
  • 1
  • 9
  • 15