Windows – Adding %USERPROFILE% to a command in the Windows registry

windows 7windows-registry

I'm trying to write a registry hack that will streamline some of my setup tasks when I create a new VM or repave my laptop. One thing I'm doing is switching to portable versions (synced in Dropbox) of a bunch of my favorite apps, including Notepad++.

I want to create a registry entry to allow me to have the Open with Notepad++ option in my right click menu, which is the only thing I'm missing with the portable version. I'm getting an error, though:

Windows cannot access the specified device, path or file. You may not have the 
appropriate permissions to access the item.

Here's my .reg file:

[HKEY_CLASSES_ROOT\*\shell\Open with Notepad++]
"Icon"="%USERPROFILE%\\Dropbox\\Programs\\Setup\\Icons\\Notepad++.ico"
@=""

[HKEY_CLASSES_ROOT\*\shell\Open with Notepad++\command]
@="%USERPROFILE%\\Dropbox\\Programs\\Notepad++\\notepad++.exe %1"

The icon works perfectly. I can get the entry above to work fine if I hardcode C:\Users\myusername, but I'm going for portability here.

I'm pretty sure the issue is just finding the right escape sequence for the % symbols, but it's hard to say.

Suggestions?

EDIT: I went with the add reg command option, and after a bit of trial and error, here's the command that worked:

reg add HKCR\*\shell\OpenWithNotepad++\command /t REG_EXPAND_SZ /ve /d ^%USERPROFILE^%"\Dropbox\Programs\Notepad++\notepad++.exe %1"

After running the command, I exported the results as a .reg file as well. Wins all around.

Best Answer

To use (expand) environment variables in the registry, the value must be of the type REG_EXPAND_SZ.

Based on this question, it would be easiest to add that kind of value with the reg command rather than a .reg file..

reg add <KEY> /v <NAME> /t REG_EXPAND_SZ /d <DATA>

See reg add /? for more information on this syntax.

You could also encode the data as hex. There's some examples of that here:

REG_EXPAND_SZ data must be presented as what MS calls a binary data type (subtype "2"), so the value must be formatted in a kind of hexidecimal format, comma-delimited, two tokens per byte (padded with zeros), with a terminating null byte of course (and further explanation is obviously far beyond the scope of this article, and the author won't be held responsible for anyone's misuse of the incomplete information given thus far). So the line above will not work but indicates the end result I wanted to achieve. As a real working .REG -file entry the example above must be rendered as:

"SoMeThIng"="%WINDIR%\\system32"

becomes

"SoMeThIng"=hex(2):22,25,57,49,4e,44,49,52,25,5c,5c,73,79,73,74,65,6d,33,32,22,00
Related Question