Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a registry key with path components via PowerShell

For a legacy application, I need to create a registry key with a name in the format c:/foo/bar/baz. (Note: forward slashes, not backslashes.) To be clear: that is a single key's name, with forward slashes, that otherwise looks like a Windows path. Because I need to script this against lots of servers, PowerShell seems like a great option.

The problem is that I cannot figure out how to create a key in that format via PowerShell. New-Item -Path HKLM:\SOFTWARE\Some\Key -Name 'c:/foo/bar/baz' errors out with PowerShell thinking I'm using / as a path separator and failing to find the path HKLM:\Software\Some\Key\c:\foo\bar, which does indeed not exist (and shouldn't). I can't find any other way to (ab)use New-Item to get what I want.

Is there something I'm missing, or should I give up and just generate and load a registry dump the old-fashioned way?

like image 441
Benjamin Pollack Avatar asked Apr 22 '13 14:04

Benjamin Pollack


People also ask

What is $PATH in PowerShell?

The Windows PATH environment variable is where applications look for executables -- meaning it can make or break a system or utility installation. Admins can use PowerShell to manage the PATH variable -- a process that entails string manipulation. To access the PATH variable, use: $env:Path.

Can you use PowerShell to edit registry?

You can still use other tools you already have available to perform filesystem copies. Any registry editing tools—including reg.exe , regini.exe , regedit.exe , and COM objects that support registry editing, such as WScript. Shell and WMI's StdRegProv class can be used from within Windows PowerShell.

How do I create a path in registry editor?

In Open, type regedit , and then click OK. The Registry Editor dialog box appears. In the left pane, expand HKEY_CURRENT_USER. Right-click Environment, and then select New → Expandable String Value from the right-click menu.


1 Answers

You need to do two things. First you need to get a writable RegistryKey object, otherwise you can't modify anything anyway. Second, use the CreateSubKey method on the RegistryKey object directly.

$writable = $true
$key = (get-item HKLM:\).OpenSubKey("SOFTWARE", $writable).CreateSubKey("C:/test")
$key.SetValue("Item 1", "Value 1")

After you create the key you use the resulting object to add values to it.

like image 145
Stefan Rusek Avatar answered Sep 21 '22 23:09

Stefan Rusek