2

I've got a NodeJS file and I run it with a Windows PowerShell script (run.ps1) that contains this line:

node ./main.js

I would like to pass command line arguments directly when I run the ps script in this way:

./run.ps1 -a firstargument -b secondargument etc...

This method doesn't work. How can I do?

UPDATE: The solution is write node ./main.js $args inside .ps1 script.

InfT
  • 41
  • 7
  • Does this answer your question? [How do I pass command line arguments to a Node.js program?](https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program) – Luuk Aug 14 '21 at 15:13

1 Answers1

1

tl;dr

If your .ps1 script doesn't explicitly declare parameters, use the automatic $args variable variable to pass all arguments it received through to your node script:

node ./main.js $args

PowerShell scripts (and functions) may explicitly declare parameters to bind arguments passed to them on invocation, using a param() block - see the conceptual about_Scripts help topic.

In the absence of parameter declarations,[1] arguments are reported via the automatic $args variable, which is a regular PowerShell array of type [object[]], whose first element ($args[0]) is the first argument.[2]

Note:

  • Passing an array such as $args to an external program passes the elements as individual arguments, which is appropriate (given that external program CLIs generally have no concept of arrays).

  • By contrast, if you invoke a PowerShell command with $args, the array is passed as a single argument, i.e. the array is passed as a whole, as the first and only positional argument.

    • To properly relay $args to PowerShell commands, use @args, which (due to $args-specific magic) even works with named arguments (e.g., -foo bar). This technique is known as splatting

[1] Technically, as long as your script or function is not an advanced one, $args can be combined with explicit parameter declarations, in that $args then only contains extra arguments, i.e. those that weren't bound to declared parameters.
By contrast, the preferable advanced scripts and functions (cmdlet-like, those that have a [CmdletBinding()] and/or [Parameter()] attributes) do not support extra arguments at all, and report an error. Supporting extra arguments in advanced scripts/functions requires declaration of a catch-all parameter, via the [Parameter() attribute's ValueFromRemainingArguments property - see this answer for an example.

[2] That is, unlike in C programs, for instance, $args doesn't also include the running script's name or path, as the first element.

mklement0
  • 382,024
  • 64
  • 607
  • 775