Reputation: 20863
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
Upvotes: 6
Views: 13193
Reputation: 36748
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
Upvotes: 11
Reputation: 8280
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)
Upvotes: 4
Reputation: 126902
$files = dir *.dat | foreach {$_.fullname}
& '.\merge outputs.ps1' -files $files
Upvotes: 3