html tool

2017年12月19日星期二

PowerShell 设置脚本入参


http://www.pstips.net/powershell-pass-args-to-scripts.html


最好的方式给参数指定名称,输入以下的脚本:
1
2
3
4
param($Directory,$FileName)
"Directory= $Directory"
"FileName=$FileName"
其中param给参数指定名称。
执行脚本:
PS E:> .MyScript.ps1 -Directory $env:windir -FileName config.xml
Directory= C:windows
FileName=config.xml
PS E:> .MyScript.ps1 -FileName config.xml -Directory $env:windir
Directory= C:windows
FileName=config.xml

验证参数

给脚本的参数绑定数据类型,绑定帮助信息。一旦脚本缺少参数,或者输入的参数类型不正确,就提醒用户:
输入脚本:
1
2
3
4
5
6
7
param(
[string]$Name=$(throw "Parameter missing: -name Name") ,
[int]$Age=$(throw "Parameter missing: -age x as number")
)
"Name= $Name"
"Age=$Age"
执行脚本:
PS E:> .MyScript.ps1
Parameter missing: -name Name
所在位置 E:MyScript.ps1:2 字符: 22
+ [string]$Name=$(throw < <<<  "Parameter missing: -name Name") ,     + CategoryInfo          : OperationStopped: (Parameter missing: -name Name:String) [], Runtime    Exception     + FullyQualifiedErrorId : Parameter missing: -name Name PS E:> .MyScript.ps1 -Name mosser
Parameter missing: -age x as number
所在位置 E:MyScript.ps1:3 字符: 18
+ [int]$Age=$(throw < <<<  "Parameter missing: -age x as number")     + CategoryInfo          : OperationStopped: (Parameter missing: -age x as number:String) [], R    untimeException     + FullyQualifiedErrorId : Parameter missing: -age x as number PS E:> .MyScript.ps1 -Name mosser -Age abc
E:MyScript.ps1 : 无法处理对参数“Age”的参数转换。无法将值“abc”转换为类型“System.Int32”。错误:
“输入字符串的格式不正确。”
所在位置 行:1 字符: 33
+ .MyScript.ps1 -Name mosser -Age < <<<  abc     + CategoryInfo          : InvalidData: (:) [MyScript.ps1], ParameterBindin...mationException     + FullyQualifiedErrorId : ParameterArgumentTransformationError,MyScript.ps1 PS E:> .MyScript.ps1 -Name mosser -Age 100
Name= mosser
Age=100

【popexizhi:
 pope用的是有默认参数的如下:
1
2
3
4
5
6
7
param(
    [string]${npldll} = "NPLDLLPATH",
    [string]${npldllnew},
    [string]${nexusExe}="NEXUSEXEPATH",
    [string]${nexusExeNew}
)
"npldllnew= ${npldllnew}"
"nexusExeNew= ${nexusExeNew}"
echo ${npldll}
echo ${npldllnew}
echo ${nexusExe}


没有评论:

发表评论