How to change specific registry setting for another user in powershell How to change specific registry setting for another user in powershell powershell powershell

How to change specific registry setting for another user in powershell


Your existing code should work for a user whose hive is already loaded (like a currently logged in user), but it makes no attempt to load the hive.

I don't know of a way to make a programmatic call to load a hive, but you can shell out to reg.exe.

This ends up being kind of janky. It seems to have issues unloading the hive if it's in use anywhere, so I've put a bunch of crap in place in this sample to try to get rid of stuff that might be holding it open, but in my tests, it can take quite a while before the reg unload command is successful, hence the whole retry portion in the finally block.

This is super unpolished, I just whipped it up on the spot.

Function GetSIDfromAcctName(){    Param(        [Parameter(mandatory=$true)]$userName    )    $myacct = Get-WmiObject Win32_UserAccount -filter "Name='$userName'"     return $myacct.sid}$user = 'someuser'$sid = GetSIDfromAcctName -userName $user$path = Resolve-Path "$env:USERPROFILE\..\$user\NTUSER.DAT"try {    reg load "HKU\$sid" $path     #New-PSDrive -Name HKUser -PSProvider Registry -Root "HKEY_USERS\$sid"    #Get-ChildItem HKUser:\    Get-ChildItem Registry::\HKEY_USERS\$sid} finally {    #Remove-PSDrive -Name HKUser    [System.GC]::Collect()    [System.GC]::WaitForPendingFinalizers()    $retryCount = 0    $retryLimit = 20    $retryTime = 1 #seconds    reg unload "HKU\$sid" #> $null    while ($LASTEXITCODE -ne 0 -and $retryCount -lt $retryLimit) {        Write-Verbose "Error unloading 'HKU\$sid', waiting and trying again." -Verbose        Start-Sleep -Seconds $retryTime        $retryCount++        reg unload "HKU\$sid"     }}

This doesn't use a PS drive, but that code is in there too, commented out.

Note that if you don't name the hive mount point with the SID, you won't actually need the SID at all because you use the username to find the NTUSER.DAT file anyway.