理解Cmdlet的位置参数

4

大家好,抱歉我是一个Power Shell的新手。目前我正在阅读《Windows PowerShell CookBook》这本书,试图开始学习它。到目前为止,除了一件事情外,所有的东西都很清晰明了,那就是我对于Cmdlet的位置参数感到非常困惑。

例如:Select-String

语法如下:

Select-String [-Pattern] <String[]> [-Path] <String[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>]
[-Encoding <String>] [-Exclude <String[]>] [-Include <String[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch]
[<CommonParameters>]

Select-String [-Pattern] <String[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <String>]
[-Exclude <String[]>] [-Include <String[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] -InputObject <PSObject>
[<CommonParameters>]

Select-String [-Pattern] <String[]> [-AllMatches] [-CaseSensitive] [-Context <Int32[]>] [-Encoding <String>]
[-Exclude <String[]>] [-Include <String[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] -LiteralPath <String[]>
[<CommonParameters>]

我可以通过忽略参数名称直接将参数值传递给Cmdlet,例如:

"Hello World"|Select-String .

基于“位置参数”的概念,因为参数-Pattern是第一个参数,所以值.可以匹配参数-Pattern。我理解得很好。

但是当我尝试使用命令行 "hello world" | Select-String -AllMatches . 时,值.不在第一位。为什么Select-String能够识别并输出结果呢?有没有人能够更详细地告诉我原理?谢谢。


找到答案了,Get-Help Select-String -Parameter * 显示参数的详细信息,其中 -Pattern 是第一个参数。谢谢。 - Joe.wang
1个回答

7
这是第一个未命名的参数。位置值告诉cmdlet哪个参数属于哪个参数。
命令将-allmatches开关链接到其参数,并将.设置为$args数组(参数数组)中的第一项,因为它没有在其前面加上-parametername。
然后,因为Select-String包括其参数的位置值,所以cmdlet知道参数数组中的第一项($args [0])应绑定到-Pattern参数。
如果您想更好地理解这一点,请阅读帮助部分中有关“参数位置”的部分,方法是运行:
Get-Help about_Parameters

请注意,在此处-Pattern参数位于第1个位置:

Get-Help select-string -Parameter pattern

-Pattern <String[]>
    Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

    To learn about regular expressions, see about_Regular_Expressions.

    Required?                    true
    Position?                    1
    Default value                
    Accept pipeline input?       false
    Accept wildcard characters?  false

然后运行以下代码,查看PowerShell如何绑定输入对象"hello world"参数以及参数值

Trace-Command -Expression { "Hello World" | Select-String -allmatches . } -Name ParameterBinding -PSHost

太好了!您将来可以回答我所有的问题。TraceGet-Help - Joe.wang
谢谢!圣诞快乐! - Joe.wang

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