在 PowerShell 中多次重复部分命令

Mar*_*ill 4 powershell command-prompt

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

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

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

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

mkl*_*nt0 5

PowerShell v4+解决方案,使用.ForEach()数组方法

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

& $command $files.ForEach({ '-f', $_ }) -other_params
Run Code Online (Sandbox Code Playgroud)

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

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

& $command ($files | ForEach-Object { '-f', $_ }) -other_params
Run Code Online (Sandbox Code Playgroud)

两种解决方案:

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

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