2017-04-25 59 views
1

這條線:ValidateScript參數驗證

[ValidateScript({if (!(Test-Path $_) -and (!($_ -like "*.exe"))) 
{ Throw "Specify correct path to executable." } 
else {$true}})] 
[String]$installerPath 

Test-Path驗證返回真/假。

但是!-like未按預期工作。使用.txt,.msi等文件類型傳遞參數不會正確驗證。

回答

3

我就簡單交換的if-else塊和除去否定(!):

[ValidateScript(
{ 
    if ((Test-Path $_) -and ($_ -like "*.exe")) 
    { 
     $true 

    } 
    else 
    { 
     Throw "Specify correct path to executable." 
    } 
}) 
3

爲了更清楚確認,我會分裂中的檢查並提供不同的錯誤消息:

[ValidateScript({ 
    if(-Not Test-Path $_){ throw "$_ does not exist." } 
    if(-Not ($_ -like "*.exe")){ throw "Input file must be an executable." } 
    $true 
})] 
[String] 
$installerPath 

因爲throw會立即退出,所以不需要「else」。