Create powershell parameter default value is curre

2019-02-10 23:40发布

I'm hoping to create a parameter who's default value is the 'current directory' (.).

For example, the Path parameter of Get-ChildItem:

PS> Get-Help Get-ChildItem -Full

-Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).

    Required?                    false
    Position?                    1
    Default value                Current directory
    Accept pipeline input?       true (ByValue, ByPropertyName)
    Accept wildcard characters?  true

I created a function with a Path parameter that accepts input from the pipeline, with a default value of .:

<#
.SYNOPSIS
Does something with paths supplied via pipeline.
.PARAMETER Path
Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#>
Function Invoke-PipelineTest {

    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
        [string[]]$Path='.'
    )
    BEGIN {}
    PROCESS {
      $Path | Foreach-Object {
        $Item = Get-Item $_
        Write-Host "Item: $Item"
      }
    }
    END {}
}

However, the . isn't interpreted as the 'current directory' in help:

PS> Get-Help Invoke-PipelineTest -Full

-Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).

    Required?                    false
    Position?                    1
    Default value                .
    Accept pipeline input?       true (ByValue, ByPropertyName)
    Accept wildcard characters?  false

What's the right way to set the Path parameter's default value to the current directory?

Incidentally, where does one set the Accept wildcard character property?

1条回答
聊天终结者
2楼-- · 2019-02-11 00:15

Use PSDefaultValue attribute to define custom description for default value. Use SupportsWildcards attribute to mark parameter as Accept wildcard characters?.

<#
.SYNOPSIS
Does something with paths supplied via pipeline.
.PARAMETER Path
Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#>
Function Invoke-PipelineTest {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
        [PSDefaultValue(Help='Description for default value.')]
        [SupportsWildcards()]
        [string[]]$Path='.'
    )
}
查看更多
登录 后发表回答