Kae Travis

Create a Registry Value and Path in One Line Using PowerShell

Here’s a useful snippet of code allowing us to create a registry value and path in one line using PowerShell.

In this example, we’re trying to write a registry name called “AlkaneName” with a value of “AlkaneValue” to a registry location that does not exist called “HKCU:\Software\Alkane”.

If we simply use:

Set-ItemProperty -Path "HKCU:\Software\Alkane" -Name "AlkaneName" -Value "AlkaneValue" -Type "String" -Force

you will see an error stating: Set-ItemProperty : Cannot find path ‘HKCU:\Software\Alkane’ because it does not exist.

We could potentially cheat by using a non-PowerShell one-liner like so:

reg add HKCU\Software\Alkane /f /v "AlkaneName" /t reg_sz /d "AlkaneValue"

But your network administrators have probably blocked users from running reg.exe so you might see this:

reg : ERROR: Registry editing has been disabled by your administrator.

Which brings us nicely to our one-liner:

If (!(Test-Path("HKCU:\Software\Alkane"))) { New-Item "HKCU:\Software\Alkane" -Force | New-ItemProperty -Name 'AlkaneName' -Value 'AlkaneValue' -Force | Out-Null; } else { Get-Item "HKCU:\Software\Alkane" | New-ItemProperty -Name 'AlkaneName' -Value 'AlkaneValue' -Force | Out-Null; } 
Create a Registry Value and Path in One Line Using PowerShell
Create a Registry Value and Path in One Line Using PowerShell

Leave a Reply