Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]
- 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{
- function validatePath {
- Param
- (
- [ValidateScript({
- if ($_ -match '^[a-z]:\[-.wd\]*$') { return $True }
- Throw "'$_' is not a valid local path."
- })]
- [string] $filePath = "C:Install"
- )
- Process
- {
- "The path is: $filePath"
- }
- }
- > validatePath # use default value
- The path is: C:Install
- > validatePath -filePath C:MyInstall # valid path
- The path is: C:MyInstall
- > validatePath -filePath NotAFullPath # invalid path -> error with custom message
- validatePath : Cannot validate argument on parameter 'filePath'.
- 'NotAFullPath' is not a valid local path.
- At line:1 char:24
- + validatePath -filePath NotAFullPath # invalid path
- + ~~~~~~~~~~~~
- + CategoryInfo : InvalidData: (:) [validatePath], ParameterBindingValidationException
- + FullyQualifiedErrorId : ParameterArgumentValidationError,validatePath
- if ([string] $args[0]) { # only true if $args[0] is neither $null nor the empty string
- validatePath -filePath $args[0]
- } else {
- validatePath
- }
- validatePath @args
- # Define a hashtable to hold the parameters, if any, to pass through
- # to validatePath() via splatting.
- $htPassthruParams = @{}
- # If the first script argument is neither $null nor the empty string,
- # add a hashtable entry for it that will bind to the -filePath parameter.
- if ([string] $args[0]) { $htPassthruParams.Add('filePath', $args[0]) }
- # Pass the hashtable with `@`, the splatting operator, to validatePath()
- validatePath @htPassthruParams
- # Define a hashtable to hold the parameters, if any, to pass through
- # to validatePath() via splatting.
- $htPassthruParams = @{}
- # Using a list of parameters, pass their values through only if they are
- # *bound*, i.e., only if they received values when the enclosing script/function
- # itself was called.
- # Assume that the enclosing script declared a -filePath parameter too.
- foreach($paramName in , 'filePath') {
- if ($PSBoundParameters.ContainsKey($paramName)) {
- $htPassthruParams.Add($paramName, $PSBoundParameters[$paramName])
- }
- }
- # Pass the hashtable with `@`, the splatting operator, to validatePath()
- validatePath @htPassthruParams
Add Comment
Please, Sign In to add comment