tl;dr
To define an array literal with strings, you must quote its elements:
$myArray = 'folder1', 'folder2', 'folder3', 'myprogram.exe'
Syntax @(...)
for array literals should be avoided. Not only is @(...)
unnecessary, it is inefficient in PowerShell versions up to 5.0, but - more importantly - it invites conceptual confusion by falsely suggesting that it constructs arrays. For more information, see the bottom section of this answer.
PowerShell has two fundamental parsing modes:
argument mode, which works like traditional shells
- In argument mode, the first token is interpreted as a command name (such as cmdlet name, function name, or filename of an executable), followed by a whitespace-separated list of arguments, which may be unquoted, if they contain neither whitespace nor shell metacharacters.
expression mode, which works like traditional programming languages, where strings must be quoted
It is the first token (excluding the LHS of a variable assignment and the =
) that determines which mode is applied - see this answer for more information.
In the following statement:
$myArray = folder1, folder2, folder3, myprogram.exe
folder1
, because it is unquoted and:
- doesn't start with
$
or (
or @
- isn't a number literal,
triggers argument mode; that is, folder1
is interpreted as the name of a command, which results in the - somewhat unhelpful - error message you saw (you can trigger it with something like Get-Date,
too).
Therefore, to define an array literal with strings, you must quote its elements:
$myArray = 'folder1', 'folder2', 'folder3', 'myprogram.exe'
Note that a - convenient, but inefficient - argument-mode alternative that spares you the effort of quoting would be the following:
$myArray = Write-Output folder1, folder2, folder3, myprogram.exe