tags:

views:

185

answers:

2

I thought I had an answer to this, but the more I play with it, the more I see it as a design flaw of Powershell.

I would like to drag and drop (or use the Send-To mechanism) to pass multiple files and/or folders as a array to a Powershell script.

Test Script

#Test.ps1
param ( [string[]] $Paths, [string] $ExampleParameter )
"Paths"
$Paths
"args"
$args

Attempt #1

I created a shortcut with the following command line and dragged some files on to it. The files come across as individual parameters which first match the script parameters positionally, with the remainder being placed in the $args array.

Shortcut for Attempt #1

powershell.exe -noprofile -noexit -file c:\Test.ps1

Wrapper Script

I found that I can do this with a wrapper script...

#TestWrapper.ps1
& .\Test.ps1 -Paths $args

Shortcut for Wrapper Script

powershell.exe -noprofile -noexit -file c:\TestWrapper.ps1

Batch File Wrapper Script

And it works through a batch file wrapper script...

REM TestWrapper.bat
SET args='%1'
:More
SHIFT
IF '%1' == '' GOTO Done
SET args=%args%,'%1'
GOTO More
:Done
Powershell.exe -noprofile -noexit -command "& {c:\test.ps1 %args%}"

Attempted Answers

Keith Hill made the excellent suggestion to use the following shortcut command line, however it did not pass the arguments correctly. Paths with spaces were split apart when they arrived at the Test.ps1 script.

powershell.exe -noprofile -noexit -command "& {c:\test1.ps1 $args}"

Has anyone found a way to do this without the extra script?

+1  A: 

Change your shortcut to this and try it:

powershell.exe -noprofile -noexit -command "& {c:\test1.ps1 $args}"
Keith Hill
Sorry, it was an elegant answer, but unfortunately, the paths arrive split by any white space in them. I've updated the question to reflect this attempt.
Nathan Hartley
No, $args is a string[] per my testing. What you are probably seeing is that if you render a string array to a string, PowerShell uses the value of $OFS to separate each entry of the array. If $OFS isn't set then PowerShell uses a space as a separator. In your script, try setting `$OFS = ', '`.
Keith Hill
Yes $args is an array, but the problem is not being caused by array expansion. When dragging files on a shortcut, Windows passes the paths separated by spaces and wrapped in quotes when necessary. Your shortcut passes the files a second time, this time without the quotes. What the script receives is a long string which it then parses by splitting it at any white spaces. I liked your idea and even tried splatting the arguments ( @args ), wrapping them as an array ( @($args) ) and adding the $OFS solution to the command line, to no avail. If you try it, you will see what I mean.
Nathan Hartley
Keith Hill
Keith, I'd up-vote your valiant attempt but I am just shy of the 15 point mark.
Nathan Hartley
A: 

I have filed a bug report on the Powershell Microsoft Connect site.

Nathan Hartley