【问题标题】:How to find the indexOf element in ArrayList in PowerShell如何在 PowerShell 中找到 ArrayList 中的 indexOf 元素
【发布时间】:2016-01-28 15:38:08
【问题描述】:

我正在尝试使用 powershell 脚本从数组列表中查找元素的索引,但是得到以下给定的错误

方法调用失败,因为 [System.String[]] 不包含 名为“IndexOf”的方法。

使用的代码:

[String[]]$eventList = New-Object System.Collections.ArrayList
$eventList.GetType().FullName 
$index = $eventList.IndexOf('cvv');

【问题讨论】:

  • 在这种情况下什么是“cvv”?
  • 遗憾的是,我认为 powershell 数组不支持 IndexOf
  • 'cvv' 是我试图在 $eventList 中找到的一个字符串,它是 null 事情是我想要 $eventList null 中的 'cvv' 的位置它应该返回 '-1' 但它是返回错误

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

您正在将 ArrayList 强制转换为数组,只需删除强制转换:

$eventList = New-Object System.Collections.ArrayList

另外,您可能需要考虑使用 List 而不是 ArrayList:

$eventList = New-Object System.Collections.Generic.List[string] 

【讨论】:

  • List<string> 赢得胜利!它还允许您根据谓词而不是字符串文字查找索引:$evenList.FindIndex({param($s) $s -match 'cv[u-z]'})
  • $s 代表列表中的项目
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 2018-09-18
  • 2016-07-24
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多