7

Here is my code :

$script={
 Write-Host "Num Args:" $args.Length;
  Write-Host $args[0]   
}

Invoke-Command  -ScriptBlock $script

When I run

  powershell.exe .\test.ps1 one two three

I got

Num Args: 0

I thought I would get

Num Args: 3
One

Something am I missing?

Thanks

3 Answers 3

8

You actually have two scopes there. The script level and the script block level. $args.Length and $args[0] will have what you are expecting at the Invoke-Command level. Inside the script block there is another scope for $args. To get the args from the command line all the way into the script block you'll need to re-pass them from Invoke-Command -ArgumentList $args.

Sign up to request clarification or add additional context in comments.

Comments

5

You need to pass the arguments to the scriptblock:

Invoke-Command  -ScriptBlock $script -ArgumentList $args 

Comments

0

You could also declare named parameters explicitly. For example:

param([switch]$someBoolSwitch=$false, [String]$nameOfSomething="some default string")

This allows you to pass in named arguments to your script, like the following example:

.\<nameOfScript.ps1> -someBoolSwitch -nameOfSomething "Slayer Roolz!"

and if you omitted -nameOfSomething "Slayer Roolz!", then $nameOfSomething would simply default to "some default sting". Similarly, $someBoolSwitch defaults to $false unless otherwise defined.

This method has the benefit of allowing you as the developer to decide which parameters are necessary and which ones can be omitted or defaulted. Furthermore, it allows the user to enter arguments in any order they like, since they're named and not positional.

One drawback to having named parameters as opposed to positional parameters is that the command-line invocation can become quite large since the user has to type in each parameter name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.