2

My Script calls a function that needs the parameters from the calling of the scripts:

function new( $args )
{
  if( $args.length -lt 8 )
  {
    Write-Host "Parameter Missing, requires 8 Parameters. Aborting."!
    Write-Host $args.length
    break
  }
}

switch ($args[0]) {
  '--test' { }
  '--new' { new $args }
  default  { }
}

When I call it, the args array is not handed over to the new function:

PS Q:\mles\etl-i_test> .\iprog.ps1 --new 1 2 3 4 5 6 7
Parameter Missing, requires 8 Parameters. Aborting. !
0

How do I pass an array to a function in powershell? Or specifically, the $args array? Shouldn't the scope for the $args array be global?

1

3 Answers 3

3

Modify your function as below:

function new { param([string[]] $paramargs)

  if( $paramargs.length -lt 8 )
  {
    Write-Host "Parameter Missing, requires 8 Parameters. Aborting."!
    Write-Host $paramargs.length
    break
  }
}

switch ($args[0]) {
  '--test' { }
  '--new' { new $args }
  default  { }
}

This will avoid the ambiguity of the variable $arg from command line and parameter $arg (changed as $paramarg).

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

2 Comments

Renaming $args to something different did the trick, thanks! is param([string[]] necessary? It works without.
Ya, param([string[]] is not required. I tried that way and posted so :)
2

The $args is always part of any function. When you call a function with $args as the name of an argument things get pretty confusing. In your function change the name to something other than $args and it should work.

function new( $arguments )
{

$arguments.Length
  if( $arguments.length -lt 8 )
  {
    Write-Host "Parameter Missing, requires 8 Parameters. Aborting."!
    Write-Host $arguments.length
    break
  }
}

switch ($args[0]) {
  '--test' { }
  '--new' { new $args }
  default  { }
}

Comments

1

You must pass $args from a parent scope to a child scope explicitly. $args in the parent scope is never visible in a chlid scope, because the scope is initialized with it's own $args. Do this:

&{get-variable -scope 0}

and note the results. Every variable you see there is created locally in the new scope when the scope is initialized, so those variables in the parent scope aren't visible in the new scope. $args is one of those variables.

1 Comment

Ah interesting. I can not overwrite $args in a function.

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.