I have written functions that have path parameters. I'm not sure if I implemented it correctly. Is there a standardized or better way of doing this in Powershell?
function Get-PathExample {
param(
[Parameter(Position=0,mandatory=$true,HelpMessage="Profilepath e.g. C:\Users or \\computername\c$\users\")]
[string]$ProfilePath,
[Parameter(Position=1,mandatory=$true,HelpMessage="SubPath e.g. AppData\Roaming\")]
[string]$SubPath
)
<#
code...
#>
}
As mentioned in the comments, your basic approach is correct - accept path stems as string arguments, then resolve and validate inside the function.
You can add the most basic level of input validation to the
paramblock itself - like validating that the$ProfilePathonly resolves to directories for example:Then inside the function you can perform more domain-specific validation - like testing that the resolved paths are indeed filesystem paths:
In the most basic scenarios - where you don't need to care about the paths themselves, but just want to resolve 1 or more provider items from a caller-supplied path - a better option is to mimic the parameter surface of the corresponding provider cmdlet (like
Get-Item) and then just offload all the heavy lifting to that command instead.To do that, use the following to generate the source code for a new parameter blocks:
On Windows you can copy the resulting code to your clipboard with
$paramBlock |Set-ClipBoardThe result will look like this:
Now manually remove the parameter definitions related to features you don't need, and you might end up with something like:
Replace the contents of your param block with the above and add a
[CmdletBinding()]decorator to set the default parameter set to the$Pathone:... at which point you can just pass the caller's parameter arguments off to
Get-Itemas-is:Now the caller can supply either wildcard paths or exact paths as they see fit, and
Get-Itemtakes care of the rest