启动时使用 Powershell 脚本的参数

问题描述:

就像在 C 和其他语言中一样,您可以在实际执行脚本时赋予 script/.exe 参数.例如:

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

Hello, 10 和 P 被传递给程序本身的某个变量.

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

这在 Powershell 中可行吗?如果是这样,你如何将这些参数赋予给定的 $variable

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

谢谢!

用这样的参数块定义你的脚本:

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.