Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PWSH – ValidateScript as reference to external ps1 script

I would like to validate my powershell function parameters with ValidateScript. Example

param (
        [ValidateScript({
                $response = (Invoke-webrequest -URI $_)
                if ($response.StatusCode -ne 200) {
                    throw "  ❌  API Nedpoint $($_) is not reachable"
                }
                
                return $true
            })]
        [Parameter(Mandatory)]
        [string]$buildURL
    )

This is valid code, but I would prefere to reference external ps1 file like

param (
        [ValidateScript(.\Validate-site.ps1)]
        [Parameter(Mandatory)]
        [string]$buildURL
    )

Which what I found is not supported like: https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/validatescript-attribute-declaration?view=powershell-7.4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If so, do you have some alternative way to validate your input for pwsh functions? Please share your code examples, or some validations which you would like to show off and are not so basic as mine.

>Solution :

You can invoke an external script with ValidateScript without a problem, but you must use a script block as argument for your validation. You can invoke it then with the Call operator &:

[ValidateScript({ & "path\to\Validate-site.ps1" })]

You were asking for examples so here is one that does not use ValidateScript and uses a custom class that inherits from ValidateEnumeratedArgumentsAttribute instead:

class ValidateUri : System.Management.Automation.ValidateEnumeratedArgumentsAttribute {
    [void] ValidateElement([object] $Object) {
        $invokeWebRequestSplat = @{
            UseBasicParsing = $true
            Method          = 'Head'
            Uri             = $Object
        }

        try {
            $response = Invoke-WebRequest @invokeWebRequestSplat
            if($response.StatusCode -ne 200) {
                throw [System.Management.Automation.ValidationMetadataException]::new(
                    "  ❌  API Nedpoint $($Object) is not reachable")
            }
        }
        catch {
            # Different error can go here
            throw [System.Management.Automation.ValidationMetadataException]::new(
                "  ❌  API Nedpoint $($Object) is not reachable")
        }
    }
}

function Test-ValidateUri {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateUri()]
        [string] $Uri
    )

    $PSBoundParameters
}

Test-ValidateUri google.com
Test-ValidateUri doesnotexist.xyz
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading