variables - 启动时使用 Powershell 脚本的参数

标签 variables powershell argument-passing

就像在 C 和其他语言中一样,您可以在实际执行脚本时赋予 script/.exe 参数。例如:
myScript.exe Hello 10 P
其中 Hello, 10 和 P 被传递给程序本身的某个变量。

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

谢谢!

最佳答案

使用 param 块定义您的脚本,如下所示:

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

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

您还可以进一步键入限定参数,例如:
-- Start of script foo2.ps1 --
param([string]$msg, [int]$num, [char]$char)

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

您还可以指定默认值和必需值,例如:
-- 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"

您可以使用高级功能(指定属性以验证参数等)变得更有趣。但这应该能让你继续前进。

关于variables - 启动时使用 Powershell 脚本的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13408440/

相关文章:

python - 在 Python Selenium 的 xpath 中使用变量

visual-studio - 是否可以在 Developer Powershell 终端中更改字体?

Java:从变量中获取变量名

function - Postgresql 将选择查询分配给函数中的变量

powershell - 使用 PSCustomObject 在单独的列中列出多个文件夹然后选择一些?

c - 在 C 中传递二维数组

r - 无法将参数传递给自己的函数中的函数

perl - 在 Perl 中,如何将函数作为另一个函数的参数传递?

java - 我应该使用静态方法还是实例方法?

powershell - Powershell:无法读取/设置ExecutionPolicy