If I were writing "idiomatic" PowerShell, what parameter types would I use for functions that work with files or directories?
For example, I made a module that contains this function:
$bookmarks = @{}
$bookmarkKeys = @{}
function Set-Bookmark {
param(
[Parameter(Mandatory = $true)]
[string] $Id,
[System.Management.Automation.DirectoryInfo] $Path = (Get-Location))
$script:bookmarks[$Id] = $Path
$script:bookmarkKeys[$Path.Path] = $Id
}
The trouble is, the following doesn't work:
PS>Set-Bookmark -Id Code -Path C:\Code
Set-Bookmark : Cannot process argument transformation on parameter 'Path'.
Cannot convert the "C:\Code" value of type "System.String" to type
"System.Management.Automation.PathInfo".
At line:1 char:29
+ Set-Bookmark -Id Code -Path C:\Code
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-Bookmark], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Bookmark
Weirdly, neither does this (but for a slightly different reason):
PS>Set-Bookmark -Id Code -Path (gi C:\Code)
Set-Bookmark : Cannot process argument transformation on parameter 'Path'.
Cannot convert the "C:\Code" value of type "System.IO.DirectoryInfo" to type
"System.Management.Automation.PathInfo".
At line:1 char:29
+ Set-Bookmark -Id Code -Path (gi C:\Code)
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-Bookmark], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Bookmark
So should I actually define my parameters as strings (i.e. the lowest common denominator) and then try to cast/parse them into the more meaningful types? This doesn't sound right, because it's a shame if I'm working with the results of things like Get-Item and they get brought down to string for passing-in, only for that function to parse back into the higher-level type again.