我想在給定一個空字符串時使用默認值。我希望更優雅的東西,然後有if語句來檢查$Var
是否爲空,並將其設置爲默認值。任何人都知道這是否可以實現?還需要支持PowerShell版本2.0。如何在powershell函數中給出空字符串時使用默認值?
下面是我試圖完成的一個片段。給定一個空字符串,我希望它打印「VAR:DEFAULT」。
$ErrorActionPreference = "Stop"
function Test-Function(
[parameter(Mandatory = $true)][string] $Var = "DEFAULT"
) {
# If Mandatory is set to $true an error is thrown
# "Cannot bind argument to parameter 'password' because it is an empty string."
# When Mandatory is set to $false, $Var is an empty string rather than "DEFAULT"
Write-Host "Var: $Var"
}
$EmptyString = ""
Test-Function -Var $EmptyString
這不使用默認值。拋出異常,指示參數爲null或空。而不是拋出這個異常,我想要使用默認值。 –
「沒有優雅的方式來做到這一點,至少沒有內建的方法可以這樣做,你可以驗證字符串不是空或空的」...與'[ValidateNotNullOrEmpty()]' –