Search and delete registry value on all users with PowerShell

In the IT Pros world, when executing commands these are usually executed within the “System Context”, or better explained with the NT System\Administrator account. The NT AUTHORITY\System account, often referred to as the “system account” or “local system,” is a built-in account in Windows operating systems. It is one of the most powerful and privileged accounts on a Windows machine and is used by the operating system itself to perform various system-level tasks.

This means that if you have a file located in %appdata%, %localappdata% or a registry located in HKCU, when you run your script for deletion, this will not delete the file/registry on the current logged in user, because you are executing the code with the NT System\Administrator account.

For the registry it is simple, we can use the following PowerShell code:

$users = Get-ChildItem “Registry::HKEY_USERS” | Where-Object { $_.PSChildName -match ‘S-1-5-21-\d+-\d+-\d+-\d+$’ }

foreach ($user in $users) {
$userSID = $user.PSChildName
$runKey = “Registry::HKEY_USERS\$userSID\Software\Microsoft\Windows\CurrentVersion\Run”

$oneDriveValue = Get-ItemProperty -Path $runKey -Name “OneDrive” -ErrorAction SilentlyContinue

if ($oneDriveValue -ne $null) {
Write-Host “User SID: $userSID”
Write-Host “OneDrive value found in registry:”
Write-Host $oneDriveValue
Write-Host “Deleting OneDrive value…”
Remove-ItemProperty -Path $runKey -Name “OneDrive” -Force
Write-Host “OneDrive value deleted.”
Write-Host “————————“


As you see, we are parsing all the users in the HKEY_USERS hive that start with 21 (these are actual users) and search on each an every one if the registry value OneDrive is found in Software\Microsoft\Windows\CurrentVersion\Run. If this is found, we delete on each user that it is found. Replace the value/location with what you need.

Leave a comment

Your email address will not be published. Required fields are marked *

2 × two =