I try to pass a number of files to a script, that must merge files together. It works fine with $args and for ($i=0; $i -lt $args.Length; $i++) as an iterator.
I want to add a check to do nothing in case only one file is passed (because there is not need to merge anything). if ($args.Length -lt 2) works when there are no arguments at all, but if I try ./myScript.ps1 "Single file name.ext", $args array contains "Single", "file" and "name.ext" as a separate elements. Is there a way to make powershell to always consider $args as an array of strings?
I also tried using params([string[]] $files), but it doesn't work even in case of ./myScript.ps1 -files "11 12","13", giving 11 as the only element of an array.
One thing more: I need file names to be separated by spaces, as far as I'm using script together with Far Manager's !&, which gives selected files as a space-separated array of double-comma surrounded strings
For example, if we have the code
if ($args.Length -lt 2)
{
Write-Host "Not enough arguments"
Exit 1
}
for ($i=0; $i -lt $args.Length; $i++)
{
Write-Host "$($args[$i])"
}
The results are
> powershell ./myScript.ps1
Not enough arguments
> powershell ./myScript.ps1 "File1" "File2" "File3"
File1
File2
File3
> powershell ./myScript.ps1 "File1"
Not enough arguments
> powershell ./myScript.ps1 "File 1"
File
1
> powershell ./myScript.ps1 "File1" "File 2" "File 3"
File1
File
2
File
3
> powershell ./myScript.ps1 'File 1' 'File 2' 'File 3'
File 1
File 2
File 3