2

In batch, passed arguments can be used with %1, and onward counting. Lets say I have the following "batch.bat" script:

@ echo off
echo %1
pause>nul

If i call this from cmd like: call batch.bat hello it would output "hello" in the console.

Is there any variable in ps which does the same thing?

EDIT

I've found the folliwing, but it seems kind of unnatural.

$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}

Is there something more elegant perhaps?

2
  • 1
    $Args array you want example $Args[0] Commented Nov 15, 2019 at 15:43
  • Thanks a lot. I tried this already but now i looked up $args and found this Commented Nov 15, 2019 at 15:48

1 Answer 1

3

PowerShell has an automatic variable $args that stores all arguments passed to a script (unless parameters were defined for the script). The individual arguments can be accessed by index ($args[0] for the first argument, $args[1] for the second, etc.).

However, in general it's advisable to define parameters to control what arguments a script should accept, e.g.

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true)]
    [string]$First,

    [Parameter(Mandatory=$false)]
    [integer]$Second = 42
)

There are numerous advantages to this, including (but not limited to):

  • arguments are parsed automatically and the values are stored in the respective variables
  • scripts automatically prompt for mandatory parameters
  • scripts throw an error if incorrect arguments are passed
  • you can define default values for optional parameters
  • you can have your script or function accept pipeline input
  • you can validate parameter values
  • you can use comment-based help for documenting the parameters and their usage
Sign up to request clarification or add additional context in comments.

2 Comments

Some additional info: in simple functions / scripts (those without [CmdletBinding()] and/or [Parameter()] attributes) $args is still defined and contains positional arguments not bound to declared parameters, if any; advanced functions / scripts fundamentally only permit passing arguments that bind to declared parameters.
Another tip: To pass all positional arguments received through to another command, use @args.

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.