Balthazar
Balthazar

Reputation: 493

Use ValidateSet Command in param block to define parameter

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?

Upvotes: 0

Views: 85

Answers (1)

4c74356b41
4c74356b41

Reputation: 72171

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 }

Upvotes: 2

Related Questions