在 PowerShell 中多次重复部分命令

Repeat part of command multiple times in PowerShell

我有一个命令保存在变量 $command 中,类似这样
$command = path\to\.exe
$command 有一个参数 -f 代表文件的路径。该参数可以在同一行中重复多次,以在多个文件上执行命令,而不必每次在每个文件上执行命令时都重新加载必要的模型。

示例:
如果我有 3 个文件,我需要打开 运行 命令,那么我可以这样执行它:

& $command -f 'file1' -f 'file2' -f 'file3' -other_params

我想知道如果我有 100 个文件,是否可以在 PowerShell 中执行此操作,因为我显然无法尝试手动传递 100 个参数。

如果我理解你的问题,这里有一个方法:

$fileList = @(
  "File 1"
  "File 2"
  "File 3"
  "File 4"
)
$argList = New-Object Collections.Generic.List[String]
$fileList | ForEach-Object {
  $argList.Add("-f")
  $argList.Add($_)
}
$OFS = " "
& $command $argList -other_params

本例中传递给 $command 的命令行参数为:

-f "File 1" -f "File 2" -f "File 3" -f "File 4" -other_params

A PowerShell v4+ 解决方案,使用 .ForEach() array method:

# Open-ended array of input file names.
$files = 'file1', 'file2', 'file3'

& $command $files.ForEach({ '-f', $_ }) -other_params

PowerShell v3- 中,通过 ForEach-Object cmdlet(效率稍低)使用以下命令:

# Open-ended array of input file names.
$files = 'file1', 'file2', 'file3'

& $command ($files | ForEach-Object { '-f', $_ }) -other_params

两种解决方案:

  • 构造一个平面字符串数组,样本输入与
    相同 '-f', 'file1', '-f', 'file2', '-f', 'file3'

  • 依赖于 PowerShell 在调用 外部程序时将数组元素作为 单独参数 传递的事实(例如 *.exe 文件)。

我不太确定您是如何构建文件列表的。我用 get-childitem 做到了这一点,希望它能替代你正在做的事情。我在这里所做的是创建一个名为 Command-Multiparam 的函数,它可以接受一个数组作为参数。然后我们对数组中的每个文件使用 foreach() 循环。

# Set your $command variable
$command = "path\to\.exe"

# First build a list of files to run the command on.
$files_list = gci "\server\folder123\*" -include "*.txt"

function Command-Multiparam{
    param(
        [Parameter(Position = 0)]
        [string[]]$files_list
        )

    foreach ($file in $files_list){ 
        & $command -f $file
    }
}

用法:Command-Multiparam $files_list

或者如果您没有使用 get-childitem 构建列表 Command-Multiparam 'file1.txt' 'file2.txt' file3.txt' 'file4.txt'