6

How does one pass a list of files as parameters to a Powershell script?

param
(
    [String[]]$files
)

echo $files

When I try to run it

PS D:\> & '.\merge outputs.ps1' *.dat

it prints

*.dat

but I expected something similar to

file1.dat
file2.dat
...
fileN.dat
2
  • Are you going to process the files one-by-one? Commented May 29, 2013 at 13:51
  • No, I will merge them all together. Commented May 29, 2013 at 14:19

3 Answers 3

11

The two solutions presented thusfar (even though one is accepted and both have upvotes) do not really provide an adequate solution to the question--they both make you jump through hoops. The question as posed stated that by just putting *.dat on the commmand line, how can one make the underlying code treat it like you would expect. That is, how to make the code simply do the right thing. With other shells and other cmdlets, all you do is *.dat, not like this:

foobar(fizzbuzz[--brobdingnag*!& '\''*.dat''`])

(OK, I exaggerate to make a point:-) But there is an easy way to just do the right thing--check if wildcards are used and then just expand them:

param
(
    [String[]]$files
)
$IsWP = [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($files)
if($IsWP) { 
    $files = Get-ChildItem $files | % { $_.Name }
}
echo $files
Sign up to request clarification or add additional context in comments.

3 Comments

To support "foo*" (or even "**"), and if the rest of the script supports full path names, use $files = Get-ChildItem $files | % { $_.FullName }.
Not clear if you are suggesting: (a) the $IsWP check is no longer needed (but it is! have to cover the case of no wildcards) or (b) one should use FullName instead of Name (but that depends upon your needs; either could work)
Right. I needed “FullName”, since I wanted to use “/” as a parameter.
4

You can either pass full file name as string

& '.\merge outputs' -files (dir *.dat | %{ $_.FullName })

Or you can accept FileSystemInfo param in your script

param
(
    [System.IO.FileSystemInfo[]]$files
)

Write-Host $files

And call:

& '.\merge outputs' -files (dir *.dat)

Comments

3
$files = dir *.dat | foreach {$_.fullname}

& '.\merge outputs.ps1' -files $files

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.