Execute PowerShell command on selected files in Explorer

青春壹個敷衍的年華 提交于 2019-12-22 14:07:12

问题


How to execute a rename command in PowerShell only on selected files in Explorer? I have the PS command but I don't know where to put it in the Windows registry to be accessible in the right-click context menu in Explorer.


回答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.




回答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).



来源:https://stackoverflow.com/questions/35178884/execute-powershell-command-on-selected-files-in-explorer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!