启动时使用 Powershell 脚本的参数 [英] Arguments with Powershell Scripts on Launch

查看:83
本文介绍了启动时使用 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.

这篇关于启动时使用 Powershell 脚本的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆