arrays - 将数组项传递给 PowerShell 中的函数

标签 arrays function powershell

我已经阅读了许多有关 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/

相关文章:

c++ - 在 C++ 类中初始化二维数组

c++ - 无法结合模板和类函数重载

python - 如何使用python从字符串定义函数

powershell - 搜索事件查看器服务器 03 和 08 r2

javascript - 检查数组中任何元素的总和是否等于给定值

javascript - 尝试返回字符串中数字的总和。如果字符串是 "99Hello1"输出是 100,如果是 "9hello9"答案是 18。遇到无知的错误

c++ - 如何传递数组并返回二维矩阵的数组值?

excel - MS Excel 在搜索功能中通过测距

html - 将 get-content 放入 html 电子邮件的数组中

azure - 如何检查 powershell 脚本是否正在 Azure 中运行