【问题标题】:PowerShell: Iterate through array to find and return value in proper casePowerShell:遍历数组以在适当的情况下查找并返回值
【发布时间】:2016-01-18 19:40:19
【问题描述】:

我正在尝试使用以下脚本遍历使用文本文件内容构建的数组并返回匹配值,如果未找到匹配则返回参数。

Param (
[string]$surname
)

$listSurnames = @(Get-Content .\MixedCaseNames.TXT)

# Return $listSurnames

$found = for($index = 0; $index -lt $listSurnames.Count; $index++) {
    if ($listSurnames[$index] -eq $surname) { return $listSurnames[$index]; break } 

    else { return $surname; break }
}

【问题讨论】:

  • 你应该看看Where-ObjectSelect-Object -First 1
  • 另外,powershell 中的return 很特别,可能不是你期望的那样。
  • "返回匹配值,如果没有找到匹配则返回参数"。什么?无论如何,您的程序的行为都会相同。
  • Get-Content .\MixedCaseNames.TXT | Where-Object{$_ -eq $surname}
  • 其次是培根。你有它返回匹配的名称,或者如果没有......你试图匹配的名称?那为什么还要麻烦翻阅文件呢?

标签: arrays file powershell text


【解决方案1】:

太棒了!谢谢你们。 :)

Param (
[string]$surname
)

$findName = Get-Content .\MixedCaseNames.TXT | Where-Object { $_ -eq $surname } | Select-Object -First 1

If ( $findName -eq $null ) { return $surname } Else { return $findName }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多