All, Forgive me I am a newbie for the Power Shell
, Currently I was reading book Windows PowerShell CookBook
try to get start with it. So far, Everything make sense to me except one thing, I was totally confused with the Positional Parameter
to Cmdlet
.
For example: Select-String
The syntax is following :
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>]
I can pass the parameter value to the Cmdlet
directly by ignoring the parameter name . like below:
"Hello World"|Select-String .
Based on the concept of Positional parameter
,Because the parameter -Pattern
is the first parameter. the value .
can match the parameter -Pattern
. It is ok for me to understand.
But When I try this command line "hello world" | Select-String -AllMatches .
the value .
is not in the first. Why the Select-String
can know it and work out the result ? Could someone please tell me more to understand it well? thanks.
It's the first unnamed paramter. The position value tells the cmdlet which argument belongs to which parameter.
The command Select-String -allmatches .
links the -allmatches
switch to its parameter, and sets the .
as the first item in the $args
-array (arguments-array) since it doesn't have -parametername
in front of it.
Then because Select-String
includes a positional value for its parameters, the cmdlet knows that the first item in the arguments-array ($args[0]
) should be bound to the -Pattern
parameter.
If you'd like to understand this better, read the part about Parameter Position?
in the help-section by running:
Get-Help about_Parameters
Then notice that the -Pattern
parameter has position 1, as seen here:
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
Then run the following line to see how PowerShell binds the inputobject "hello world"
and the parameters and arguments.
Trace-Command -Expression { "Hello World" | Select-String -allmatches . } -Name ParameterBinding -PSHost
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With