简体   繁体   中英

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!

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 eg:

-- 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 eg:

-- 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM