What is the proper way to receive a file as a parameter when writing a C# cmdlet? So far I just have a property LiteralPath (aligning with their parameter naming convention) th
This is how you can handle Path
input in a PowerShell script cmdlet:
function My-Cmdlet {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact='Medium')]
Param(
# The path to the location of a file. You can also pipe a path to My-Cmdlet.
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]] $Path
)
Begin {
...
}
Process {
# ignore empty values
# resolve the path
# Convert it to remove provider path
foreach($curPath in ($Path | Where-Object {$_} | Resolve-Path | Convert-Path)) {
# test wether the input is a file
if(Test-Path $curPath -PathType Leaf) {
# now we have a valid path
# confirm
if ($PsCmdLet.ShouldProcess($curPath)) {
# for example
Write-Host $curPath
}
}
}
}
End {
...
}
}
You can invoke this method in the following ways:
With a direct path:
My-Cmdlet .
With a wildcard string:
My-Cmdlet *.txt
With an actual file:
My-Cmdlet .\PowerShell_transcript.20130714003415.txt
With a set of files in a variable:
$x = Get-ChildItem *.txt
My-Cmdlet -Path $x
Or with the name only:
My-Cmdlet -Path $x.Name
Or by pasing the set of files via the pipeline:
$x | My-Cmdlet