12

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?

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I thought FogBugz had keys like this, but the slashes go the other way: i42.tinypic.com/154jzac.jpg
@DannyTuppeny You guessed the software, but they're actually forward slashes in my original question. PowerShell is just using the fact that UNC paths treat "\" and "/" identically to make my life annoying.
@BenjaminPollack Oops, didn't read the question properly! Seems like this "helpful" feature might make it impossible to do natively. You could call out to .NET, but obviously that's not ideal :-(
in powershell there is no such things as calling "out to .net". Powershell is 100% .net.
@StefanRusek I was referring to using the .NET classes directly rather than the PowerShell cmdlets/providers :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.