0

I need to write a function which defines a bool Parameter automatically with [ValidateScript()].

function Deploy-App {
    Param(
        [Parameter(Position=0)]
        [ValidateScript({if (Test-Path .\DeployFiles.txt) { $UseFilepathFile = $true }})]
        [Alias("u")]
        [bool]$UseFilepathFile
    )

    Get-Location
    Write-Host $UseFilepathFile
}

Why does this always return $false even though the file exists in the current location? Is the usage of ValidateScript() wrong and I can't use it like this? How else would I tackle my problem?

1
  • Your code doesn't make sense. ValidateScript() is for validating values passed into a function, not for assigning values to variables. The latter would go into the function bod, e.g. $UseFilepathFile = Test-Path .\DeployFiles.txt. Please take a step back and describe the actual problem you're trying to solve. What do you need this for? Commented Dec 10, 2016 at 16:52

1 Answer 1

2

You are using ValidateScript the wrong way, ValidateScript is used to validate the input, not set it. Also, you must return $true from the ValidateScript, else the script won't work.

What you need is to check if that file exists inside the body of the script itself.

if (Test-Path .\DeployFiles.txt) { $UseFilepathFile = $true }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.