While converting a few .reg files to .ps1, I’ve run into a problem with this script:
$key = "Registry::HKEY_CLASSES_ROOT\*\shell\Open with Notepad"
New-Item -Path $key"\Command" -Value "Notepad.exe `"%1`"" -Force
New-ItemProperty -Path $key -Name "Icon" -Value "Notepad.exe" -PropertyType String -Force
While New-Item creates the key just fine, New-ItemProperty is getting hung up on the astrix in the path, interpreting it as a wildcard. Is there any way around this?
Use single quotes instead of double quotes around your key string. Single quotes indicate a string literal.
$key = 'Registry::HKEY_CLASSES_ROOT\*\shell\Open with Notepad'
New-Item -Path $key"\Command" -Value "Notepad.exe `"%1`"" -Force
New-ItemProperty -Path $key -Name "Icon" -Value "Notepad.exe" -PropertyType String -Force
Alternately, if you want to use double quotes, you can use a back tick to tell powershell not to interpret the special meaning of *
$key = "Registry::HKEY_CLASSES_ROOT\`*\shell\Open with Notepad"
New-Item -Path $key"\Command" -Value "Notepad.exe `"%1`"" -Force
New-ItemProperty -Path $key -Name "Icon" -Value "Notepad.exe" -PropertyType String -Force
system
January 14, 2016, 11:25am
3
That’s not the first time I’ve seen PowerShell’s path abstractions have problems with the realities of the registry. (It also has trouble with paths that contain forward slashes in a key name.)
You can work around this by using the underlying .NET methods instead:
$hive = [Microsoft.Win32.RegistryKey]::OpenBaseKey('ClassesRoot', 'Default')
$subKey = $hive.CreateSubKey('*\shell\Open with Notepad', $true)
$subkey.SetValue('Icon', 'Notepad.exe', 'String')
$subKey = $subKey.CreateSubKey('Command', $true)
$subkey.SetValue($null, "Notepad.exe `"%1`"", 'String')
I’m not 100% sure if I’ve translated your code properly, but you can run this and then verify the proper keys / values with regedit.
Thanks, for the tip about the single quotes, Curtis. I wasn’t aware they’re treated differently. Unfortunately neither option worked in this case.
Your code worked perfectly, Dave. Thanks! I guess these cmdlets never expected to have to deal with these otherwise illegal characters.
I tested with the escape character and it worked for me. Granted, the New-ItemProperty took a while, but it completed.
$key = "Registry::HKEY_CLASSES_ROOT\`*\shell\Open with Notepad"
New-Item -Path $key"\Command" -Value "Notepad.exe `"%1`"" -Force
New-ItemProperty -Path $key -Name "Icon" -Value "Notepad.exe" -PropertyType String