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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.