Reputation: 43
I have a command which I saved in the variable $command
, something like this
$command = path\to\.exe
The $command
has a parameter -f
which represents the path to the file. This parameter can be repeated multiple times in the same line to execute the command on multiple files without having to reload the necessary models every time the command is executed on each file.
Example:
If I have 3 files I need the run the command on, then I can execute it like this:
& $command -f 'file1' -f 'file2' -f 'file3' -other_params
I want to know if there is any way to do this in PowerShell if I have 100 files since I can't obviously try to pass in 100 parameters manually.
Upvotes: 4
Views: 3880
Reputation: 437090
A PowerShell v4+ solution, using the .ForEach()
array method:
# Open-ended array of input file names.
$files = 'file1', 'file2', 'file3'
& $command $files.ForEach({ '-f', $_ }) -other_params
In PowerShell v3-, use the following, via the ForEach-Object
cmdlet (which is slightly less efficient):
# Open-ended array of input file names.
$files = 'file1', 'file2', 'file3'
& $command ($files | ForEach-Object { '-f', $_ }) -other_params
Both solutions:
construct a flat array of strings that with the sample input is the same as
'-f', 'file1', '-f', 'file2', '-f', 'file3'
rely on the fact that PowerShell passes the elements of an array as individual arguments when invoking an external program (such as an *.exe
file).
Upvotes: 5
Reputation: 1351
I'm not really sure how you are building your file list. I did it with get-childitem hoping that would be a suitable replacement for however you're doing it. What I did here was make a function called Command-Multiparam
which can accept an array as a param. Then we use a foreach()
loop on each file in the array.
# 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
}
}
Usage: Command-Multiparam $files_list
Or if you didn't build your list with get-childitem
Command-Multiparam 'file1.txt' 'file2.txt' file3.txt' 'file4.txt'
Upvotes: 1
Reputation: 24525
If I understand your question, here's one way:
$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
The command line parameters passed to $command
in this example will be:
-f "File 1" -f "File 2" -f "File 3" -f "File 4" -other_params
Upvotes: 2