如何在 PowerShell 中强制设置参数?
如何在 PowerShell 中强制设置参数?
How do I make parameters mandatory in PowerShell?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 PowerShell 中强制设置参数?
How do I make parameters mandatory in PowerShell?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
您可以在每个参数上方的属性中指定它,如下所示:
You specify it in an attribute above each parameter like this:
要使参数成为强制参数,请在参数描述中添加“Mandatory=$true”。要使参数可选,只需保留“强制”语句即可。
此代码适用于脚本和函数参数:
确保“param”语句是脚本或函数中的第一个语句(注释和空行除外)。
您可以使用“Get-Help”cmdlet 来验证参数是否已正确定义:
To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out.
This code works for both script and function parameters:
Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.
You can use the "Get-Help" cmdlet to verify the parameters have been defined correctly:
只是想发布另一个解决方案,因为我发现 param(...) 块有点难看。
看起来像这样的代码:
也可以像这样写得更简洁:
看起来好多了!
=$true
可以省略,因为mandatory
是一个开关参数。just wanted to post another solution, since i find
param(...)
blocks kind of ugly.looks like this code:
can also be written more concisely like this:
which looks much nicer! the
=$true
can be omitted becausemandatory
is a switch parameter.您不必指定
Mandatory=true
,Mandatory
就足够了。简单示例:
You don't have to specify
Mandatory=true
,Mandatory
is enough.Simple Example: