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("\")
$subkeys = $key.split("\")
foreach ($subkey in $subkeys)
{
{
#Extend $currentkey with the current element of
#the array:
$currentkey += ($subkey + '\')
$currentkey += ($subkey + '\')
#Check if $currentkey already exists in the registry
if (!(Test-Path $currentkey))
{
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
}
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:
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!
}
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!
You should not "type" the $Value argument, a packed binary won't work.
ReplyDeleteOther than that, nice recursive addition.
Solution for the binary is to remove the [String] before the value, then it works for binary
ReplyDeleteNew-RegistryKey -key "" -name "" -type binary -value "1,2,0,0,12"
The binary value needs to be in decimals
Hex: 0f
Dec : 16