"Open PowerShell window here" File Explorer context-menu command breaks with folder names with apostrophes (single quotes)

In Windows 10, Shift-right-clicking on a folder or in the background in File Explorer adds an "OpenPowerShell window here" command to the context menu.

However, the command used to open the PowerShell window is ill-defined (as of at least W10 release ID 1709) in that it incorrectly assumes that folder names never contain embedded ' characters:

# !! Breaks with folder names such as "a'b"
powershell.exe -noexit -command Set-Location -literalPath '%V' 

See below for a fix, but note that it requires administrative privileges.


Solution 1:

Note:

  • This fix requires administrative privileges.
  • CAVEAT: Because, due to the use of "...", PowerShell evaluates the specified path as it would evaluate an argument PowerShell-internally, the command can break with with folder names such as $foo - or, worse, result in execution of commands through carefully - and maliciously - crafted folder names.

Open regedit.exe and apply the following steps to both of the following registry keys: HKEY_CLASSES_ROOT\Directory\shell\Powershell\command and
HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell\command:

  • Preparation: modify the permissions so that modification of the value (the PowerShell command) becomes possible:

    • Right-click on the command subkey and select Permissions...

    • Click on Advanced and:

      • make the Administrators group the owner of the key
      • give the Administrators group full control of the key
    • Note: I am not aware of any adverse effects of these modifications, but do tell us if you know of any.
      However, to be safe, you may revert these modifications after modifying the command as described below, which entails restoring the TrustedInstaller security principal as the owner of the command key; note that you must specify it as
      NT SERVICE\TrustedInstaller.

  • Now replace the command key's (Default) value with the following command:
    powershell.exe -noexit -command Set-Location -literalPath \"%V\"

It should be possible to script the above steps.