我已经阅读了许多有关 PowerShell 函数以及向它们传递参数的文章,但我还没有找到有关如何将特定数组项传递给函数而不是完整数组的解决方案。
这就是我的代码的样子:
$log = "C:\Temp\test.txt"
$test = "asdf"
$arrtest = @("one", "two", "three")
Function Write-Log($message)
{
Write-Host $message
$message | Out-File $log -Append
}
现在我想将数组的单个项目传递给 Write-Log 函数,如下所示:
Write-Log "first arr item: $arrtest[0]"
Write-Log "second arr item: $arrtest[1]"
Write-Log "third arr item: $arrtest[2]"
但在命令行中,我总是会得到完整的数组加上 [number] 作为字符串:
first arr item: one two three[0]
second arr item: one two three[1]
third arr item: one two three[2]
我认为问题出在我的语法上,有人可以指出我正确的方向吗?
非常感谢!!
最佳答案
这就能解决问题:
写入日志“第一个 arr 项:$($arrtest[0])”
在您的尝试中,您传递了整个数组,因为 PowerShell 将 $arrtest
解释为变量,将 [0]
解释为字符串。
关于arrays - 将数组项传递给 PowerShell 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406546/