1

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?

Omglolyes
  • 156
  • 11

1 Answers1

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    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. – mklement0 Nov 15 '19 at 16:06
  • Another tip: To pass all positional arguments received through to another command, use `@args`. – mklement0 Sep 05 '22 at 20:12