在 PowerShell 中访问 $args 数组
Rohan Timalsina
2023年1月30日
PowerShell
PowerShell Array
$args 是一个数组,因此你可以传递多个值并在 PowerShell 脚本或函数中访问它们。本教程将介绍 PowerShell 中的 $args 数组。
在 PowerShell 中使用 $args 数组
$args 存储传递给脚本或函数的未声明参数的值,是 PowerShell 创建和维护的自动变量之一。
例如,此函数从输入中获取参数。
function test_args(){
Write-Host "First argument is $($args[0])"
Write-Host "Second argument is $($args[1])"
}
子表达式运算符 $() 允许你在另一个表达式中使用一个表达式。它将结果转换为双引号 " " 内的字符串表达式。
如果你调用函数 test_args 并传递参数,它会返回以下输出。
test_args Hello World
输出:
First argument is Hello
Second argument is World
参数从 args[] 数组中的零开始按升序传递。例如,第一个值存储在 [0],第二个存储在 [1],第三个存储在 [2],依此类推。
在 PowerShell 中使用 $args[]
你还可以使用 $args[] 按位置引用特定参数。我们创建了一个包含以下命令的 myscript.ps1 脚本。
$name=$args[0]
$age=$args[1]
Write-Host "My name is $name."
Write-Host "I am $age years old."
调用脚本并传递参数。
.\myscript.ps1 John 21
输出:
My name is John.
I am 21 years old.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Rohan Timalsina
