Can a validation script alter the parameter itself?

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 8 months ago.

  • Author
    Posts
  • #5626

    by scottbass at 2013-03-04 23:14:05

    Test script foo.ps1
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
    [Parameter(
    Position = 0,
    Mandatory=$true
    )]
    [ValidateScript({
    if ($_.GetType().Fullname -like "System.IO.*") {$_ = $_.Fullname}
    $true
    })]
    [Object[]]$Path
    )
    $Path
    $Path | % {$_.GetType().Fullname}

    # call using path (string)
    .\foo.ps1 c:\temp\temp1

    The "real script" will call GCI against the path string(s), retrieving the children.

    # call using System.IO objects (either files or directories)
    $files=gci c:\temp\temp1
    .\foo.ps1 $files

    In this second scenario, I need the full path to the file objects. If I just cast the System.IO objects to strings (by changing the parameter type declaration from [Object[]] to [String[]]), I get relative paths, and the GCI call later in the script fails.

    Can reformatting of the input parameter be accomplished via a validation script?

    by mjolinor at 2013-03-05 05:44:00

    I don't think so. The validation script block is going to run in it's own scope. You can set a variable there, but that instantiates a new variable, and it goes away when the validation script finishes and the scope is disposed.

You must be logged in to reply to this topic.