组合默认参数和参数集



我有一个PowerShell脚本,可以获取csv中指定的主机的数据,如果给定一个开关reboot,还会尝试重新启动主机。因此,只有在重新启动的情况下,才需要凭据。

我的参数块如下所示:

[CmdletBinding(DefaultParametersetName = 'None')] 
Param(
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[ValidateScript( {
if ( -Not ($_ | Test-Path) ) {
throw "Source $_ does not exist"
}
return $true
})]
$path= $(Join-Path $PWD.Path "sources.csv"),
[Parameter(ParameterSetName = 'Extra', Mandatory = $false)]
[switch]$reboot,
[Parameter(ParameterSetName = 'Extra', Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential] $credential = $(Get-Credential -UserName myUser)
)

我的期望:仅当给出reboot时,才会提示用户输入凭据。 但是,无论给出什么参数,都会显示凭据弹出窗口。

我假设与默认值有关。

这里根本不需要参数集。只需使用空凭据即可使用以下方法初始化$credential参数:

[CmdletBinding()] 
Param(
[ValidateNotNullOrEmpty()]
[ValidateScript( {
if ( -Not ($_ | Test-Path -PathType Leaf) ) {
throw "Source $_ does not exist"
}
return $true
})]
$path = $(Join-Path $PWD.Path "sources.csv"),
[switch]$reboot,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]$credential = [System.Management.Automation.PSCredential]::Empty
)
# if no credential is given prompt for it
if ($credential -eq [System.Management.Automation.PSCredential]::Empty) {
$credential = Get-Credential -UserName myUser -Message 'Please enter your username and password'
}
# rest of your code goes here

希望有帮助

最新更新