Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments with Powershell Scripts on Launch

Like in C and other languages, you can give to the script/.exe arguments when you physically execute the script. For example:

myScript.exe Hello 10 P

Whereby Hello, 10 and P are passed to some variable in the program itself.

Is this possible in Powershell? and if so, how do you give those args to a given $variable

Thanks!

like image 640
PnP Avatar asked Nov 16 '12 00:11

PnP


2 Answers

Define your script with a param block like so:

-- Start of script foo.ps1 --
param($msg, $num, $char)

"You passed in $msg, $num and $char"

You can further type qualify parameters as well e.g:

-- Start of script foo2.ps1 --
param([string]$msg, [int]$num, [char]$char)

"You passed in $msg, $num and $char"

You can also specify default values and required values e.g.:

-- Start of script foo3.ps1 --
param([string]$msg=$(throw "Msg param is required"), [int]$num, [char]$char="P")

"You passed in $msg, $num and $char"

You can get even fancier with advanced functions (specify attributes to validate parameters, etc). But this should get you going.

like image 185
Keith Hill Avatar answered Oct 15 '22 12:10

Keith Hill


Just a complement to @Keith Hill answer ...

As you talk about 'C', you can also write a scripts with parameters using the automatic variable $args.

$Args Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.

-- Start of script foo3.ps1 --
if ($args.length -gt 0)
{
  write-host "first param is $($args[0])"
}

for ($i=0 ; $i -lt $args.length ; $i++)
{
  write-host "$i) " $args[$i]
}

you can call thr script

.\foo3.ps1 coucou bonjour "hello world"
first param is coucou
0)  coucou
1)  bonjour
2)  hello world
like image 38
JPBlanc Avatar answered Oct 15 '22 11:10

JPBlanc