拖放多个文件到批处理文件到powershell中处理

h43kikqp  于 2023-06-29  发布在  Shell
关注(0)|答案(1)|浏览(134)

我正试图将多个Excel文件拖放到批处理文件中,并将每个Excel文件处理到PowerShell中。
我有它的大部分下来,但问题是我不能得到的filename只和不能通过变量“DroppedFiles”作为一个数组。

批量文件

@echo off

SET ScriptDirectory=%~dp0
SET ScriptFile=%ScriptDirectory%Tool.ps1

for %%I in (%*) do (
     set DroppedFiles=%%I
)
powershell.exe -ExecutionPolicy Bypass -File "%ScriptFile%" "ScriptDirectory" "DroppedFiles"

Tool.ps1脚本

param($env:ScriptDirectory=$args[1],
      $env:DroppedFiles=$args[2])

$env:ScriptDirectory
$env:DroppedFiles

# Get the Files that I ONLY Dragged onto the Batch File
$Input = Get-ChildItem $PWD | Where {$_.Name -match $env:DroppedFiles}
kxeu7u2r

kxeu7u2r1#

按如下所示重写批处理文件:

@echo off

:: Pass the full paths of the dropped files directly to PowerShell
powershell.exe -ExecutionPolicy Bypass -File "%~dp0Tool.ps1" %*

重写PowerShell脚本,如下所示:

# Get information about the dropped files via their full paths, 
# reflected in the automatic $args variable.
$fileInfos = Get-ChildItem -LiteralPath $args

上面的代码简化了你的代码,并绕过了它的问题,特别是:

  • 可能包含空格的路径缺少双引号(SET ScriptDirectory=%~dp0
  • 无法使用for /?在单个变量中迭代地构建一个 * 列表 *(这只适用于 * 延迟的 * 变量扩展)。
  • %...%"ScriptDirectory""DroppedFiles")中没有封装定义的变量
  • 在PowerShell方面:
  • 应避免将自动$input变量用于 * 自定义 * 目的。
  • 使用自动的$args变量 * 而不是正式声明参数。
  • 不要使用$env:(环境变量)作为 parameter 变量。

相关问题