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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With