Parameters 将参数传递到脚本中
因此,我创建了一个函数,它根据建议的准则工作。但是,我对脚本有一个问题。我有一个函数,其中参数在函数后面。但我希望参数是代码块上方脚本中的第一件事,如本例所示:Parameters 将参数传递到脚本中,parameters,powershell-3.0,Parameters,Powershell 3.0,因此,我创建了一个函数,它根据建议的准则工作。但是,我对脚本有一个问题。我有一个函数,其中参数在函数后面。但我希望参数是代码块上方脚本中的第一件事,如本例所示: param(statement) body of script 但当我将参数放在代码上方时,什么也不会发生: Function proper { param([switch]$allcaps,[string]$title="") if($allcaps) { $title.ToUpper() }
param(statement)
body of script
但当我将参数放在代码上方时,什么也不会发生:
Function proper {
param([switch]$allcaps,[string]$title="")
if($allcaps) {
$title.ToUpper()
} else {
Foreach($string in $Title) {
$splitstr=$string.Split(" ")
$out=@()
Foreach($word in $splitstr) {
$out+="{0}{1}" -f $word.Substring(0,1).ToUpper(),$word.substring(1).ToLower()
if($out -ne 1) {
$out = $out -replace 'A','a'
$out = $out -replace 'THE','the'
$out = $out -replace 'BUT','but'
$out = $out -replace 'OR','or'
$out = $out -replace 'AT' , 'at'
$out = $out -replace 'OF','of'
$out = $out -replace'TO','to'
$out = $out -replace'WITH','with'
$out = $out -replace'IN','in'
$out[0] = $out[0] -replace 'a','A'
$out[0] = $out[0] -replace 'the','The'
$out[0] = $out[0] -replace 'but', 'But'
$out[0] = $out[0] -replace'or','Or'
$out[0] = $out[0] -replace'at','At'
$out[0] = $out[0] -replace'of','Of'
$out[0] = $out[0] -replace'to','To'
$out[0] = $out[0] -replace'with','With'
$out[0] = $out[0] -replace'in','In'
}
}
}
}
}
普通PowerShell脚本的参数以-,开头,例如:
script.ps1 -server http://devserver
然后在文件开头的param部分处理它们(请参见教程:)
您还可以为参数指定默认值,如果不可用,则从控制台读取,或停止脚本执行:
param (
[string]$server = "http://defaultserver",
[string]$username = $(throw "-username is required."),
[string]$password = $( Read-Host "Input password, please" )
)
在脚本中,您可以简单地
write-output $server
因为所有参数都成为脚本范围内可用的变量
在本例中,如果在不调用脚本的情况下调用脚本,$server将获得一个默认值,如果省略-username参数,脚本将停止,如果省略-password,脚本将请求终端输入
更新:您可能还需要向PowerShell脚本传递一个“标志”(布尔真/假参数)。例如,您的脚本可能接受一个“force”,当不使用force时,脚本将以更谨慎的模式运行
其关键字为[switch]参数类型:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
在脚本中,您可以这样使用它:
if ($force) {
//deletes a file or does something "bad"
}
.\yourscript.ps1 -server "http://otherserver" -force
现在,在调用脚本时,您可以如下设置switch/flag参数:
if ($force) {
//deletes a file or does something "bad"
}
.\yourscript.ps1 -server "http://otherserver" -force
如果您明确地想要声明未设置该标志,则有一种特殊的语法
.\yourscript.ps1 -server "http://otherserver" -force:$false