windows 批处理脚本打开文件选择器对话框或将文件拖放到其中

A windows batch script open a file chooser dialog or drag-and-drop file to it

我尝试编写一个批处理脚本,当您将另一个文件拖放到其中时,它会执行一些操作。如果你不放下任何东西,只需双击它,它会打开一个文件选择对话框window。

第一部分很简单:

@echo off
bin\dosomething "%~1"

对于第二部分,我用谷歌搜索了这个主题:

它也有效。

但是,我不能将这两个合二为一。我试过了

if "%~1" == [] goto select

然后在第二部分前加上:select,就是不行。代码如下:

@ECHO OFF
if "%~1" == [] goto select
bin\dosomething "%~1"
goto :EOF

:select

<# : chooser.bat
:: launches a File... Open sort of file chooser and outputs choice(s) to the console
:: 

@echo off
setlocal

for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
    echo You chose %%~I
    bin\dosomething "%%~I"
)
goto :EOF

: end Batch portion / begin PowerShell hybrid chimera #>

Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }

我试了If "%~1"=="",它按目的跳了,但是对话框windows还是没有出现,CMD直接输出错误行为:

You chose + iex (${D:\Program Files (x86)\BBB\choose list file.bat} | out-strin ...

已解决

解决了。只有“%~1”正确。

我在这里粘贴代码:

<# : chooser.bat

:: drop file to execute, or open a file chooser dialog window to execute.
:: code mostly comes from 

@ECHO OFF

if "%~1" == "" goto SELECT
bin\dosomething "%~1"
goto :EOF

:SELECT

setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
    echo You chose %%~I
    bin\dosomething "%%~I"
)
goto :EOF

: end Batch portion / begin PowerShell hybrid chimera #>

Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }

这些混合脚本的诀窍在于,隐藏 Powershell 解析器的批处理代码并隐藏批处理解析器的 Powershell 代码。

对于Powershell,<##>之间的部分是注释。值得庆幸的是 <# : comment 对批处理解析器没有坏处。因此,您的批处理代码应该在该 Powershell 注释中。

另一方面,最后一个批处理命令是 goto :EOF,这意味着下面的所有命令(Powershell 的 "end of comment" 行和 Powershell 代码本身)将被批处理忽略解析器。

所以只需将您的行 <# : chooser.bat 移到第一行。