Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong type checking for non existent file declared in a function parameter

Tags:

powershell

I am writing a PowerShell function that carries out some operation on a file, the path to the file is passed to the function as a parameter. I'm a fan of strong typing and parameter validation so instead of just passing the file path as a System.String I've defined the parameter like so:

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PathInfo]$PathInfo

Normally I would use Resolve-Path in the calling code to get an object of type System.Management.Automation.PathInfo that I could pass to this parameter however in this case it is legitimate for the file to not yet exist and hence Resolve-Path would throw an error.

Is it possible to instantiate an instance of System.Management.Automation.PathInfo for a none-existent file? If so, how? If not, do you have a suggestion for how I might pass a non-existent file path to a function and still have strong type checking.

like image 591
jamiet Avatar asked Nov 04 '15 11:11

jamiet


1 Answers

Although using the [System.IO.FileInfo] type would probably be the neatest solution in this case (doing something to a file), you might run into problems if you're given a path to a folder, since .Exists returns False in such cases. You'd want to use [System.IO.DirectoryInfo] instead...

Thinking a bit more generally you could use a validation script, esp. one that calls some sort of testing function, for example the following should allow parameters that are either $null or a valid [System.Management.Automation.PathInfo] type.

function Test-Parameter {
  param($PathInfo)

  if([System.String]::IsNullOrEmpty($PathInfo)) {
    return $true

  } elseif($PathInfo -is [System.Management.Automation.PathInfo]) {
    return $true

  } else {
    return $false
  }
}

And then you use this a [ValidateScript({...})] check your parameter meets those (arbitrary) conditions:

function Do-Something {
  param(
    [Parameter()]
      [ValidateScript({Test-Parameter $_})]
      $PathInfo
  )

  ....
}
like image 129
Charlie Joynt Avatar answered Nov 09 '22 10:11

Charlie Joynt