简体   繁体   English

将脚本参数传递给Powershell中的函数

[英]Passing script parameters to a function in Powershell

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: 当我调用它时,args数组不会移交给new函数:

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? 如何将数组传递给Powershell中的函数? Or specifically, the $args array? 还是具体地说,$ args数组? Shouldn't the scope for the $args array be global? $ args数组的作用域不应该是全局的吗?

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 ). 这将避免命令行中的变量$arg和参数$arg的歧义(更改为$paramarg )。

The $args is always part of any function. $args始终是任何函数的一部分。 When you call a function with $args as the name of an argument things get pretty confusing. 当您使用$args作为参数名称调用函数时,事情变得很混乱。 In your function change the name to something other than $args and it should work. 在函数中,将名称更改为$args以外的名称,它应该可以工作。

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  { }
}

You must pass $args from a parent scope to a child scope explicitly. 您必须将$ args从父作用域明确传递给子作用域。 $args in the parent scope is never visible in a chlid scope, because the scope is initialized with it's own $args. 父范围中的$ args在chlid范围中永远不可见,因为该范围是使用其自己的$ 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. $ args是这些变量之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM