param(
[Parameter(Mandatory = $true , HelpMessage = "Enter a domain like facebook.com")]
[ValidateScript({
try {
$_ -like "*.*"
}
catch {
throw "Enter a domain like facebook.com."
}
})][string]$Domain
)
我正在嘗試學習在引數中進行錯誤檢查。我知道如何在if. 從我讀到的內容來看,這應該可以,但是當發送給 Facebook 時,我會收到以下錯誤。它適用于 facebook.com
錯誤
Cannot validate argument on parameter 'Domain'. The "
try {
$_ -like "*.*"
}
catch {
throw "Enter a domain like facebook.com."
}
" validation script for the argument with value "facebook" did not return a result of True. Determine why the validation script failed,
and then try the command again.
At line:1 char:1
. {
~~~
CategoryInfo : InvalidData: (:) [], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationError
我究竟做錯了什么?
uj5u.com熱心網友回復:
您當前的try陳述句不會拋出錯誤,因此它永遠不會運行catch。您還可以拋出更好的錯誤型別
您的驗證腳本應該看起來更接近這個:
param(
[ValidateScript({
if ($_ -like "*.*") {
$true
}
else {
Throw [System.Management.Automation.ValidationMetadataException] "Enter a domain like facebook.com."
}
})][string]$Domain
)
您可以在驗證腳本中使用 try/catch,但前提是實際的 try 塊回傳錯誤
uj5u.com熱心網友回復:
您可以使用ValidatePattern正則運算式
[ValidatePattern('.*\..*')]
在 Powershell 7ErrorMessage中添加了引數
[ValidatePattern('.*\..*', ErrorMessage = "your message")]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513265.html
標籤:电源外壳
