Tech News

How to Take Ownership of a Registry Key in PowerShell

I had to write a PowerShell script to take ownership of the mentioned registry keys. The code is only quick to show we can do it (after all PowerShell has no limits) and could be improved error handling and so on. Here is how to do it.

Take ownership of a registry key in PowerShell

$definition = @"
using System;
using System.Runtime.InteropServices;

namespace Win32Api

    public class NtDll
        [DllImport("ntdll.dll", EntryPoint="RtlAdjustPrivilege")]
        public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool Enabled);

Add-Type -TypeDefinition $definition -PassThru

$bEnabled = $false

# Enable SeTakeOwnershipPrivilege
$res = [Win32Api.NtDll]::RtlAdjustPrivilege(9, $true, $false, [ref]$bEnabled)

$key = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("DesktopBackground\Shell\Display", [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
$acl = $key.GetAccessControl()

No comments