Search code examples
parameterspowershell-3.0

Pass multiple parameters using variables with PowerShell


I'm trying to get a command to work in PowerShell using a variable to contain a list of files to process as an argument to an executable at the command line.

If I hardcode the file names, it'll work. If I pass the files in by variable, it does not. I want to use a variable because I don't always know in advance how many files there will be. The idea is to dynamically build the file list into the variable, and then pass that to the PS script.

[string] $userID       = 'MyUserID'
[string] $hostID       = 'MyHost' 
[string] $userPwd      = 'blahblahblah'
[string] $pathToExe    = 'C:\MyFolder\MyExecutable.exe'
[string] $pathToFiles  = 'C:\MyFolder2\MyFiles'
[string] $fileList     = 'File1.txt', 'File2.txt', 'File3.txt'

Set-Location -Path $pathTofiles

# This works
& $pathToExe /hostID=$hostID /arg2=$userID /arg3=userPwd File1.txt File2.txt File3.txt


# This does NOT work - says the files cannot be found
& $pathToExe /hostID=$hostID /arg2=$userID /arg3=userPwd $fileList

I have even tried setting $fileList = 'File1.txt File2.txt File3.txt' but that did not work either.

Any ideas?

Thanks! James


Solution

  • Define $fileList as

    [string[]] $fileList = 'File1.txt', 'File2.txt', 'File3.txt'
    

    Then you can use your syntax

    & $pathToExe /hostID=$hostID /arg2=$userID /arg3=userPwd $fileList
    

    or you can apply splatting (introduced in Windows PowerShell 3.0, imho) as follows:

    & $pathToExe /hostID=$hostID /arg2=$userID /arg3=userPwd @fileList