Arguments with Powershell Scripts on Launch

廉价感情. 提交于 2020-01-02 02:35:12

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/13408440/arguments-with-powershell-scripts-on-launch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!