Search code examples
validationpowershelldefault-value

Combine a default parameter value with validation via the ValidateScript attribute


I have the following PowerShell code to validate user input as a path, if the user didn't enter anything, I am attempting to assign a default value to them. However when I run this, the $filePath variable does not gets assigned any value.

Is there anyway I can change this to have it assigned a default value while the validation is going on?

Code below:

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

validatePath -filePath $args[0] 

Solution

  • I think you could drop the validate script and instead do this in a Begin block:

    Begin{
        If ($filepath -eq "") {
            $filepath = "C:\Install"
        }
        ElseIf ($filepath -notmatch "^([a-z]:\\(?:[-\\w\\.\\d])*)") {
            Write-Error "Please enter a valid path,$filepath is not a valid path."
        }
    }
    Process{