我正在尝试使用自定义属性将多个变量传递到一个foreach语句中,但是自定义属性未在foreach语句内传递
$input = "one two three"
$tests = "true false true"
Add-Member -InputObject $tests -MemberType NoteProperty -Name "Name" -Value $input
foreach ($test in $tests) {
Write-Host $test.Name
Write-Host $test
}
预期输出:
one
true
two
false
three
true
任何帮助将不胜感激。
因此,有很多事情要解决。首先,foreach
循环对数组起作用。因此,您的变量声明是错误的。它必须以逗号分隔,或者必须为数组格式。
像这样
$input = "one", "two", "three"
$tests = "true", "false", "true"
要么
$input = @("one", "two", "three")
$tests = @("true", "false", "true")
Foreach
循环不能同时处理多个数组; 在你的情况下,你应该使用For
像
$input = "one", "two", "three"
$tests = "true", "false", "true"
foreach ($test in $tests) ## For looping through single array
{
Write-Host $test
}
If($input.Length -match $tests.Length) ## Forlooping through multiple arrays
{
For($i=0;$i -lt $input.Length; $i++)
{
"$($input[$i]) :: $($tests[$i])"
}
}
对于您的期望格式,应为:
$input = "one", "two", "three"
$tests = @("true", "false", "true")
If($input.Length -match $tests.Length)
{
For($i=0;$i -lt $input.Length; $i++)
{
"$($input[$i])"
"$($tests[$i])"
}
}
输出:
one
true
two
false
three
true
PS:现在您可以轻松地基Add-Member -InputObject $tests -MemberType NoteProperty -Name "Name" -Value $input
于此逻辑合并。
希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句