Execute PowerShell command on selected files in Explorer

Solution 1:

HKCR:\*\shell contains what you need. Create a new key with the name of what you want to call it (eg "Rename With Date"), then a subkey called "Command" with a default value of your command.

So for example, HKCR:\*\shell\Rename With Date\Command where the (Default) value is PowerShell -Command Rename-Item "%1" ((Get-Date).ToShortDateString() + " - %1") or something should do the trick I think.

Solution 2:

It is fairly easy to add a context-menu command to selected files in File Explorer using Powershell's New-Item cmdlet to write a command line to the registry:

# Add a context-menu item named 'Foo' to the context menu of files 
# that executes a PowerShell command that - in this simple demonstration - 
# simply *echoes* the file path given, using Write-Output.
$null = New-Item -Force "HKCU:\Software\Classes\*\shell\Foo\command" | 
        New-ItemProperty -Name '(Default)' -Value `
         "$PSHOME\powershell.exe -NoProfile -NoExit -Command Write-Output \`"%1\`""

The above targets HKCU:\Software\Classes\*\shell (HKEY_CURRENT_USER\Software\Classes\*\shell) and therefore applies to files only; the folder-only location is HKCU:\Software\Classes\Folder\shell, and the location for both files and folders is HKCU:\Software\Classes\AllFileSystemObjects\shell.
Also note the use of -LiteralPath above, which is crucial to prevent interpretation of the * in HKCU:\Software\Classes\* as a wildcard.
Note that writing to the equivalent HKEY_LOCAL_MACHINE keys so as to make the command available to all users would require elevation (running as administrator).

The caveat is that with this approach the command is invoked for each selected file, should multiple files be selected.

In other words: if your intent is to rename a group of files and your renaming logic requires that the group be considered as a whole, the above approach won't work.

You could try to work around that in the script itself, but that would be nontrivial.

A more robust solution is to create context-menu handlers, which requires writing "in-process Component Object Model (COM) objects implemented as DLLs" (from the docs).