2017-02-28 31 views
0

完脚本我在我的powershell脚本以下代码来验证用户输入(在脚本中的第一位置参数):当Powershell的输入验证失败或产生异常

function validatePath { 
Param 
(
    [Parameter(Mandatory=$true)] 
    [ValidateScript({ 
     If ($_ -match "^([a-z]:\\(?:[-\\w\\.\\d])*)") { 
      $True 
     } Else { 
      Write-Host "Please enter a valid path,$_ is not a valid path." 
      Write-debug $_.Exception 
      Break 
     } 
    })] 
    [string]$filePath 
) 
Process 
{ 
    Write-Host "The path is "$filePath 
} 
} 

validatePath -filePath $args[0] 

我的问题是,目前在验证失败,代码进入Else块并击中Break,而不是停止继续运行整个脚本,它会转到下一个块,所有事情都会继续,并出现更多错误。

问题是,我该如何修改我的代码,以便在验证失败时匹配正则表达式,它会抛出相应的错误消息并停止运行整个脚本?

回答

1

设置脚本里面的$ErrorActionPreference变量Stop

$ErrorActionPreference = 'Stop' 

function validatePath { 
Param 
(
    [Parameter(Mandatory=$true)] 
    [ValidateScript({ 
     If ($_ -match "^([a-z]:\\(?:[-\\w\\.\\d])*)") { 
      $True 
     } Else { 
      Write-Host "Please enter a valid path,$_ is not a valid path." 
      Write-debug $_.Exception 
      Break 
     } 
    })] 
    [string]$filePath 
) 
Process 
{ 
    Write-Host "The path is "$filePath 
} 
} 

validatePath -filePath $args[0] 
Do-MoreStuff # this won't execute if parameter validation fails in the previous call 

更多信息,请参见about_Preference_Variables help file

+0

它工作!谢谢! –

0

使用 “退出” 停止整个脚本。在“退出”之前放置任何消息。

+0

不起作用,我在块内设置退出后脚本仍在继续。 –

相关问题