How do I deal with Paths when writing a PowerShell Cmdlet?

后端 未结 2 633
故里飘歌
故里飘歌 2021-01-30 01:57

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

2条回答
  •  误落风尘
    2021-01-30 02:05

    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
    

提交回复
热议问题