Getting ALL Your Parameters

When you write a function, you can name a set of parameters and PowerShell will bind command line arguments to them. Any command line argument that is NOT bound do a parameter is available as $args. Let me illustrate:

PS>function test ($a) {“Remaing args = $args”}
PS>test -A value
Remaing args =
PS>
PS>test -A value -B value2 -C this is a test
Remaing args = -B value2 -C this is a test
PS>
PS>function test ($a,$b,$c) {“Remaing args = $args”}
PS>test -A value -B value2 -C this is a test
Remaing args = is a test

Eric asked me the question, “How can I get ALL the arguments and not just the “remaining arguments”. You can get this but it requires a tiny amount of work on your part. If you haven’t already explored $MYINVOCATION – you should. This variable tells you about how your function was invoked. It is awesome! One of its properties is LINE which provides the “line” that was submitted which caused your function to get invoked. Again, an example makes this clear:

PS>function test {$myinvocation}
PS>test -A Value -b Value2 -c Value3 this is a test


MyCommand : test
ScriptLineNumber : 1
OffsetInLine : 5
ScriptName :
Line : test -A Value -b Value2 -c Value3 this is a test
PositionMessage :
At line:1 char:5
+ test <<<< -A Value -b Value2 -c Value3 this is a test
InvocationName : test
PipelineLength : 1
PipelinePosition : 1

PS>write-host “test”;test -A Value -b Value2 -c Value3 this is a test
test


MyCommand : test
ScriptLineNumber : 1
OffsetInLine : 23
ScriptName :
Line : write-host “test”;test -A Value -b Value2 -c Value3 this is a test
PositionMessage :
At line:1 char:23
+ write-host “test”;test <<<< -A Value -b Value2 -c Value3 this is a test
InvocationName : test
PipelineLength : 1
PipelinePosition : 1

From there you have the building blocks to get your answer. The OffsetInLine tells you where the args start:

PS>function test {$myinvocation.line.substring($myInvocation.OffSetInLine)}
PS>write-host “PowerShell”;test -A Value -b Value2 -c Value3 this is a test
PowerShell
-A Value -b Value2 -c Value3 this is a test


This isn’t a perfect solution because it doesn’t address other things on the line:


PS>write-host “PowerShell”;test -A Value -b Value2 -c Value3 this is a test; write-Host “Rocks”
PowerShell
-A Value -b Value2 -c Value3 this is a test; write-Host “Rocks”
Rocks

Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx