代码之家  ›  专栏  ›  技术社区  ›  Harry

Powershell参数未按预期工作[重复]

  •  -1
  • Harry  · 技术社区  · 6 年前

    Param block ,我有一个简单的程序来获取这两个值并打印它,但是当我运行下面的代码时,它会要求输入 secondvalue 但是跳过了 first value

    为什么它不要求 firstvalue 作为输入?

    function print {
        Param(
        [Parameter(mandatory = $true)] $firstvalue,          
        [Parameter(mandatory = $true)] $secondvalue
    )
        write-host first : $firstvalue
        write-host second : $secondvalue    
    }
    
    print($firstvalue, $secondvalue)
    

     ./first.ps1 
    
    cmdlet print at command pipeline position 1
    Supply values for the following parameters:
    secondvalue: second data
    first :  
    second : second data
    

    谢谢, 感谢您的帮助。

    2 回复  |  直到 6 年前
        1
  •  1
  •   lit    6 年前

    核心问题是当 print

    print($firstvalue, $secondvalue)
    

    圆括号创建一个包含两个元素的数组$firstvalue和$secondvalue。数组被解释为为$firstvalue提供的值,但是$secondvalue没有任何内容。由于需要$secondvalue,因此会发生错误。尝试使用:

    print $firstvalue $secondvalue
    
        2
  •  1
  •   Robert Rice    6 年前

    在我看来,你的参数块很有用。

    function print {
        Param(
        [Parameter(mandatory = $true)] $firstvalue,          
        [Parameter(mandatory = $true)] $secondvalue
    )
    
        write-host first : $firstvalue
        write-host second : $secondvalue    
    }
    
    print
    

    这也许有帮助。 about_Functions