PowerShell - 为什么不'包含'处理从数组中拉出的字符串?

时间:2013-01-30 13:39:04

标签: arrays string powershell contains

试图解决这个问题并且没有太多运气。来自以下代码块的if语句永远不会成立,我不明白:

$array1 = "red", "blue", "green", "yellow"
$array2 = "rose", "sky", "grass", "sand"
$both_arrays = $array1, $array2

for ($c=0; $c -lt 4; $c++) {

$object = $both_arrays[0][$c]
$colour = $both_arrays[1][$c]

Write-Host $c "-" $object
Write-Host $c "-" $colour

if ( ($colour.contains("green") ) ) { Write-Host "HELL YEAH! Green is my favourite colour!" }

}

输出如下:

0 - red
0 - rose
1 - blue
1 - sky
2 - green
2 - grass
3 - yellow
3 - sand

如果我们只处理一个数组,它可以正常工作:

$array1 = "red", "blue", "green", "yellow"

for ($c=0; $c -lt 4; $c++) {

$colour = $array1[$c]

Write-Host $c "-" $colour

if ( ($colour.contains("green") ) ) { Write-Host "HELL YEAH! Green is my favourite colour!" }

}

输出按预期结束:

0 - red
1 - blue
2 - green
HELL YEAH! Green is my favourite colour!
3 - yellow

涂抹是怎么回事?帮助赞赏!

当我尝试将该概念应用于我写的另一个脚本时,上述代码仍然出现错误:

for ($c=0; $c -lt 3; $c++) { #$arrCheckpoint, 

$ckname = $arrCheckpointNameAndStatus[0][$c]
$ckstatus = $arrCheckpointNameAndStatus[1][$c]

Write-Host $ckname

if ( ($ckname.contains("Standard Checkpoint") ) ) { Write-Host "Hit." }

}

Write-Host "End of Script"

它会抛出以下错误:

Method invocation failed because [System.Object[]] doesn't contain a method named 'contains'.
At C:\script.ps1:225 char:27
+     if ( ($ckname.contains <<<< ("Standard Checkpoint") ) ) { Write-Host "Hit." }
+ CategoryInfo          : InvalidOperation: (contains:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

现在真的开始误解我了!

1 个答案:

答案 0 :(得分:1)

您似乎对对象和颜色数组的数组索引进行了反转。