创建 PowerShell 参数默认值为当前目录。

3
我希望创建一个参数,其默认值为“当前目录”(.)。
例如,Get-ChildItemPath参数:
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

我创建了一个带有 Path 参数的函数,该参数可以从管道中接收输入,默认值为 .

<#
.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 {}
}

然而,在帮助文档中,.并不被解释为“当前目录”。
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

如何将 Path 参数的默认值设置为当前目录?

顺便问一下,接受通配符字符 属性应该在哪里设置?


你确定这不仅仅是函数内部的魔法和“当前目录”的字面默认值吗?(我假设它不会那么傻,而是某种明确的东西,但我也假设你可能无法直接在PowerShell中复制它。) - Etan Reisner
我想那是可能的,但对我来说似乎有些粗糙。当前目录这个值会根据Windows本地化而改变吗? - craig
我假设字符串是本地化的,无论内部实现如何。话虽如此,我不希望在内部使用与该值的比较。我期望使用“给定的值是否有效”的测试,因为 $null 在这里没有意义。 - Etan Reisner
1个回答

7
使用PSDefaultValue属性来定义默认值的自定义描述。使用SupportsWildcards属性将参数标记为接受通配符字符?
<#
.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='.'
    )
}

3
我理解为微软没兴趣更新文档?叹气 - Ansgar Wiechers
1
相关 - craig
我会把这个当作“是”的回答。 ;) - Ansgar Wiechers
@AnsgarWiechers 我不在微软工作,所以无法代表他们回答。你可以通过在 Microsoft Connect 上提交工单来打扰他们。 - user4003407

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接