如何将多个参数传递给 PowerShell 中的函数? [英] How do I pass multiple parameters into a function in PowerShell?

查看:49
本文介绍了如何将多个参数传递给 PowerShell 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个接受多个字符串参数的函数,第一个参数似乎获取分配给它的所有数据,其余参数作为空传入.

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.

快速测试脚本:

Function Test([string]$arg1, [string]$arg2)
{
    Write-Host "`$arg1 value: $arg1"
    Write-Host "`$arg2 value: $arg2"
}

Test("ABC", "DEF")

生成的输出为

$arg1 value: ABC DEF
$arg2 value: 

正确的输出应该是:

$arg1 value: ABC
$arg2 value: DEF

这在多台机器上的 v1 和 v2 之间似乎是一致的,所以很明显,我做错了什么.谁能指出具体是什么?

This seems to be consistent between v1 and v2 on multiple machines, so obviously, I'm doing something wrong. Can anyone point out exactly what?

推荐答案

PowerShell(所有版本)中函数调用中的参数以空格分隔,而不是逗号分隔.此外,括号是完全不必要的,如果 Set-StrictMode -Version 2 或更高版本处于活动状态.括号中的参数仅用于 .NET 方法.

Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {
   "a: $a; b: $b; c: $c"
}

ps> foo 1 2 3
a: 1; b: 2; c: 3

这篇关于如何将多个参数传递给 PowerShell 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆