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?

Benjamin Pollack
  • 27,594
  • 16
  • 81
  • 105

1 Answers1

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.

Benjamin Pollack
  • 27,594
  • 16
  • 81
  • 105
Stefan Rusek
  • 4,737
  • 2
  • 28
  • 25
  • 1
    I thought FogBugz had keys like this, but the slashes go the other way: http://i42.tinypic.com/154jzac.jpg – Danny Tuppeny Apr 22 '13 at 14:35
  • @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. – Benjamin Pollack Apr 22 '13 at 14:36
  • @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 :-( – Danny Tuppeny Apr 22 '13 at 16:05
  • in powershell there is no such things as calling "out to .net". Powershell is 100% .net. – Stefan Rusek Apr 22 '13 at 21:29
  • @StefanRusek I was referring to using the .NET classes directly rather than the PowerShell cmdlets/providers :-) – Danny Tuppeny Apr 23 '13 at 14:43