Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
Try using param(...) - stackoverflow.com/a/12425338/763026 – Angshuman Agarwal Apr 5 at 14:46

3 Answers

up vote 2 down vote accepted

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).

share|improve this answer
Renaming $args to something different did the trick, thanks! is param([string[]] necessary? It works without. – mles Apr 5 at 15:44
Ya, param([string[]] is not required. I tried that way and posted so :) – RinoTom Apr 6 at 17:41

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.

share|improve this answer
Ah interesting. I can not overwrite $args in a function. – mles Apr 5 at 15:43

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  { }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.