我創建了一個函式來查找陣列中的專案,以便我可以更新它。
function Get-ArrayRowIndex {
param(
[parameter(mandatory = $true)][array]$Property,
[parameter(mandatory = $true)][string]$Value
)
#Loop through array,incrementing index until value is found. Jordan wrote this and I refined it.
[int]$index = 0
while ($index -lt ($Property.count)) {
if ($Property[$index] -eq $Value) {
break
}
$index
}
return [int]$index
}
問題是當找不到物件時,函式回傳陣列中的專案總數。如果沒有找到如何回傳錯誤?
uj5u.com熱心網友回復:
如果您想在找不到該值的情況下拋出錯誤:
function Get-ArrayRowIndex {
param(
[parameter(mandatory = $true)][array]$Property,
[parameter(mandatory = $true)][string]$Value
)
[int]$index = 0
while ($index -lt ($Property.count)) {
if ($Property[$index] -eq $Value) {
# Found -> output the value and return (exit) here.
return $index
}
$index
}
# Getting here means that the value wasn't found.
throw "'$Value' not found in the given array."
}
請注意,您可以使用該[Array]::FindIndex()方法而不是自己回圈遍歷陣列:
# Returns the index if found; -1 otherwise.
[Array]::FindIndex(
$Property,
[Predicate[object]] { $Value -eq $args[0] }
)
[Array].IndexOf()是另一種選擇,但前提是需要區分大小寫的字串比較(而 PowerShell 的運算子,例如-eq上面使用的,默認情況下不區分大小寫);例如,('FOO', 'bar').IndexOf('foo')產量-1(未找到)和 ('FOO', 'foo').IndexOf('foo')產量1
uj5u.com熱心網友回復:
通常,for回圈是一種更清潔的方法:
function Get-ArrayRowIndex {
param(
[parameter(mandatory = $true)][array]$Property,
[parameter(mandatory = $true)][string]$Value
)
for($i = 0; $i -lt $Property.Count; $i )
{
if($Property[$i] -eq $Value)
{
return $i
}
}
throw "$Value not found in this array."
}
$arr = 0..10
Get-ArrayRowIndex $arr 4 # => returns 4
Get-ArrayRowIndex $arr 11 # => throws "11 not found in this array."
uj5u.com熱心網友回復:
PowerShell 方式,使用Select-String:
$Properties = 'One', 'Two', 'Three'
$Value = 'Two'
($Properties |Select-String -SimpleMatch -Pattern $Value).LineNumber
2
拋出錯誤:
$Found = $Properties |Select-String -SimpleMatch -Pattern $Value
Switch ($Found.Count) {
0 { Throw "$Value not found" }
1 { $Found.LineNumber }
Default { Throw "More than one $Value found" }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405514.html
標籤:
