Running powershell scripts by drag-n-drop file or folder on it
Is there any way of running a powershell script by drag-n-dropping a file on it (just like you would drag-n-drop a file on a .exe file)? It would be also nice to be able to do the same thing with folders...
12 Answers
Create a Windows Explorer shortcut (In Explorer right click -> new -> shortcut). Then right-click on your shortcut and open the Properties dialog box. In the Target field enter something like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -noprofile -file C:\yourscriptdirectory\yourscript.ps1Whether you need the -noexit or -noprofile options is up to you, take a look at the help to decide.
Now when you drop a file (or folder) onto this shortcut, explorer will magically pass it as the first argument to your script.
The above shortcut works when you drop one file on the shortcut file. The fully qualified filename will be passed as the first parameter of the called PowerShell script.
You may also drop multiple files. These can either be picked up as $Args array parameters or in a named parameter by using the [Parameter(ValueFromRemainingArguments=$true)] specification in your PowerShell script.
See my summary on Stack Overflow at Dragging and Dropping Files onto a PowerShell Script --- Additional Information and Solutions
- The posting also describes how to use a .BAT file instead of a Shortcut file to pass dropped file names to a PowerShell script.
- In a 2nd posting I give a way to have the PowerShell script also expand and process files in any dropped directories.