Search This Blog

Monday, June 18, 2012

Powershell: Set registry key

The New-Item CmdLet is used to create a registry key normally:
New-Item -Type String "HKLM:\Software\Example"

This works fine but that can be a roundabout way if you need to create a key whose subkeys are not existing:
New-Item -Type String "HKLM:\Software\Example"
New-Item -Type String "HKLM:\Software\Example\Sub1"
New-Item -Type String "HKLM:\Software\Example\Sub1\NewKey"


Last but not least, you have to set the value:
Set-ItemProperty "HKLM:\Software\Example\Sub1\NewKey" "Name" -value "John Doe" -type String


With the following function you are able to set an registry key and its value:

Function New-RegistryKey([string]$key,[string]$Name,[string]$type,[string]$value)
{
    #Split the registry path into its single keys and save
    #them in an array, use \ as delimiter:
    $subkeys = $key.split("\")
    
      #Do this for all elements in the array:
    foreach ($subkey in $subkeys)
    {
        #Extend $currentkey with the current element of
        #the array:
        $currentkey += ($subkey + '\')

        #Check if $currentkey already exists in the registry
        if (!(Test-Path $currentkey))
        {
            #If no, create it and send Powershell output
            #to null (don't show it)
            New-Item -Type String $currentkey | Out-Null
        }
     }
     #Set (or change if alreday exists) the value for $currentkey
      Set-ItemProperty $CurrentKey $Name -value $Value -type $type 
}

Function Call:
New-RegistryKey "<PATH>" "<NAME>" "<DATATYPE>" "<VALUE>"

Datatypes:
  • String
  • ExpandString (for use with environment variables)
  • Binary
  • DWord
  • Multistring
  • QWord

Example:
New-RegistryKey "HKLM:\Software\Vendor\MySoftware\2012\Example\Another\Key\StopHere" "Name" "STRING" "John Doe"

NO GUARANTEE THAT THIS FUNCTION WORKS WITHOUT ANY ERRORS IN YOUR ENVIRONMENT - PLEASE TEST IT FIRST!

2 comments:

  1. You should not "type" the $Value argument, a packed binary won't work.

    Other than that, nice recursive addition.

    ReplyDelete
  2. Solution for the binary is to remove the [String] before the value, then it works for binary

    New-RegistryKey -key "" -name "" -type binary -value "1,2,0,0,12"

    The binary value needs to be in decimals

    Hex: 0f
    Dec : 16

    ReplyDelete