1

I know that in PowerShell an array can be created as follows.

$myArray = "item1", "item2", "item3"

or using another syntax.

$myfruits = @('Pineapple','Oranges','Bananas')

I need to create an array that has names of directories and a file found in the script root.

$myArray = folder1, folder2, folder3, myprogram.exe

The items in the array are actual names of folders and an executable without quotes as they are found in the current directory (script root). This does not work with PowerShell giving error Missing argument in Parameter list. What am I doing wrong? I'm on Windows 10 x64 using PowerShell 7.0.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Amani
  • 16,245
  • 29
  • 103
  • 153

1 Answers1

1

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
mklement0
  • 382,024
  • 64
  • 607
  • 775