【问题标题】:PowerShell - why doesn't 'contains' work on a string pulled from an array?PowerShell - 为什么“包含”对从数组中提取的字符串不起作用?
【发布时间】:2013-01-14 08:25:53
【问题描述】:

试图解决这个问题,但真的没有太多运气。以下代码块中的 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

smeg 是怎么回事?感谢您的帮助!

当我尝试将这个概念应用到我正在编写的另一个脚本时,上面的代码示例仍然出现错误:

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

现在真的开始烦我了!

【问题讨论】:

    标签: arrays string powershell contains


    【解决方案1】:

    您的对象和颜色数组的数组索引似乎颠倒了。

    【讨论】:

    • 哦... * 尴尬* 应该是 1,0,而不是 0,1... 我觉得自己笨吗:D
    猜你喜欢
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多