我正在编写一个 .ps1 PowerShell 脚本,我想知道如何找到用户传递了多少个参数。例如,我需要我的程序来处理检查多个文件中的字符串。所以用户应该能够输入
./脚本“a”ex1.txt
或
./脚本“a” ex1.txt ex2.txt
我知道在 Bash 中我们可以使用 $#
,但是如何在 PowerShell 中检查?
最佳答案
在脚本或函数中,您可以访问通过自动填充的 $args
变量传入的参数。 $args
是一个数组,因此您可以找到通过其 Count
属性传递的参数数量。
一个例子:
function PrintArgs()
{
Write-Host "You passed $($args.Count) arguments:"
$args | Write-Host
}
调用PrintArgs
:
> PrintArgs 'a' 'b' 'c'
You passed 3 arguments:
a
b
c
关于PowerShell - 如何计算参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490543/