Using environment variables in registry strings.

As part of my job, I receive zip files which I want to do some processing on. I wrote a powershell script to do this processing for me and it’s been really useful. However, even having to fire up Powershell and type in the commands to execute it has become a complete chore (I’m a very lazy person!).

So I decided to add a context-menu item to Windows Explorer for .zip files which would run the script for me.

My initial script looked like this, but had a couple of flaws:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.zip\shell\PS Import]
@="Do Powershell Import"

[HKEY_CLASSES_ROOT\.zip\shell\PS Import\command]
@="%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe \"& '%User_Profile%\\Documents\\my_script.ps1' '%1'\""

The first issue I came across was that I was adding the registry keys to HKEY_CLASSES_ROOT\.zip. This turned out to be incorrect. The correct location was HKEY_CLASSES_ROOT\CompressedFolder.

The second issue is that the default value for a registry key is a REG_SZ (a registry string). This would have been fine, except that I was using environment variables (%SystemRoot% and %UserProfile%) in my path. It turns out that these don’t get expanded at runtime.

Instead, I would need to make the default value for the key of type REG_EXPAND_SZ, which is a registry string which will expand variables.

So my new script looks like this:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\CompressedFolder\shell\PS Import]
@="Do Powershell Import"

[HKEY_CLASSES_ROOT\CompressedFolder\shell\PS Import\command]

Obviously, this is not directly maintainable. The only way I can maintain it is to edit the string in the registry, then export the shell key to a new reg file.

The final issue I found was when I was writing this post at home. Here, I have WinRar installed, so I also needed to add the same keys to HKEY_CLASSES_ROOT\WINRAR.ZIP\shell, and I added it into HKEY_CLASSES_ROOT\.zip\shell for good luck. If anyone can explain a little bit about how Windows goes about looking up the context menu in the registry for a given extension, I’d really appreciate it!