拖放至 Powershell 脚本 [英] Drag and Drop to a Powershell script

查看:92
本文介绍了拖放至 Powershell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我对此有答案,但我玩得越多,就越认为这是 Powershell 的设计缺陷.

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.

我想通过拖放(或使用发送至机制)将多个文件和/或文件夹作为数组传递给 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.ps1
param ( [string[]] $Paths, [string] $ExampleParameter )
"Paths"
$Paths
"args"
$args

尝试 #1

我使用以下命令行创建了一个快捷方式,并将一些文件拖到其中.这些文件作为单独的参数出现,首先在位置上匹配脚本参数,其余的放在 $args 数组中.

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.

尝试 #1 的捷径

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

包装脚本

我发现我可以使用包装脚本来做到这一点...

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

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

包装脚本的快捷方式

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

批处理文件包装脚本

它通过批处理文件包装脚本工作...

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%}"

尝试回答

Keith Hill 提出了出色的建议使用以下快捷命令行,但它没有正确传递参数.带有空格的路径在到达 Test.ps1 脚本时被分开.

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?

推荐答案

自从它可用以来,一直以来的秘密就是参数属性ValueFromRemainingArguments".

The secret all this time, since it was made available, has been the parameter attribute "ValueFromRemainingArguments".

快捷方式、批处理或 CMD 文件以接收丢弃的文件

5.1 或更早版本

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

Powershell 6 及更新版本

Powershell 6 and newer

pwsh.exe -noexit -file c:\Test.ps1

Test.ps1

[CmdletBinding()]
param (
    [Parameter(ValueFromRemainingArguments=$true)]
    $Path
)

$Path

TestExpandDirectories.ps1

[CmdletBinding()]
param (
    [Parameter(ValueFromRemainingArguments=$true)]
    $Path
)

foreach ($aPath in $Path) {
    $aPath
    if (Test-Path $aPath -PathType Container) {
        Get-ChildItem $aPath -Recurse | Select-Object -ExpandProperty FullName
    }
}

这篇关于拖放至 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆