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
To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.
The script must define a parameter to receive the path & filename from the double-click (note that Param declarations must be prior to any other code) "Param([String]$FileNameSelected)". The script must use the param $FileNameSelected as an argument when launching a program.
The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test . Get-ChildItem displays the files and directories in the PowerShell console. By default Get-ChildItem lists the mode (Attributes), LastWriteTime, file size (Length), and the Name of the item.
Note that if you pass a folder path to Powershell that has a trailing backslash it cannot handle it. e.g. -ParamFolder "C:\project folder\app\bin debug\". The parameter string ends up with a double quote at the end.
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
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)
$files = dir *.dat | foreach {$_.fullname}
& '.\merge outputs.ps1' -files $files
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