Thursday, April 25, 2019

How to get environment variables of the current logged on user, when running scheduled tasks or powershell as the System Account (NtAuthority\System)


While running a scheduled task that I needed to run as the local System account, I noticed that any environment variables were not accessible the normal method inside of Powershell, which was quite the kink. I need access to the logged on user credentials and the documents folder path and there is very little if anything available via search engines that document this, so here we are.

New-PSDrive HKU Registry HKEY_USERS;
$user = get-wmiobject -Class Win32_Computersystem | select Username;
$sid = (New-Object System.Security.Principal.NTAccount($user.UserName)).Translate([System.Security.Principal.SecurityIdentifier]).value;
$val = (Get-Item "HKU:\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
$myDocPath = $val.GetValue("Personal");




If you follow the instructions via this link, you can open powershell as the NTAuthority\System account to test/troubleshoot, etc.
http://powershell-guru.com/powershell-tip-53-run-powershell-as-system/

Enjoy.

No comments:

Post a Comment