查找对象数组的索引

Gar*_*ett 4 arrays powershell indexof

当使用值数组时,indexof可用于查找值在数组中的位置。

#this returns '1', correctly identifying 'blue' in position '1' of the array
$valueArray = @('cup','blue','orange','bicycle')
[array]::indexof($valueArray,'blue')
Run Code Online (Sandbox Code Playgroud)

我想使用此命令来查找使用 生成的对象数组中文件(图像)的位置Get-ChildItem,但是无论我调用的对象实际在哪里,返回的位置始终为“-1”。请注意,image123.jpg 位于数组的中间。

$imageArray = Get-ChildItem "C:\Images"
[array]::indexof($imageArray,'image123.jpg')
Run Code Online (Sandbox Code Playgroud)

我注意到,如果我仅将数组更改为文件名,它会返回文件名的实际位置。

$imageArray = Get-ChildItem "C:\Images" | select -expand Name
[array]::indexof($imagesToReview,'image123.jpg')
Run Code Online (Sandbox Code Playgroud)

这只是使用的本质indexof还是有办法在不转换的情况下找到数组中图像文件的正确位置?

Adm*_*ngs 8

最简单的解决方案如下:

$imageArray = Get-ChildItem "C:\Images"
[array]::indexof($imageArray.Name,'image123.jpg')
Run Code Online (Sandbox Code Playgroud)

解释:

[array]::IndexOf(array array,System.Object value)在一个对象中搜索一个array对象value。如果未找到匹配项,则返回array下限减 1。由于数组的第一个索引是0,因此它返回 的结果0-1

Get-ChildItem -Path SomePathDirectoryInfo返回和对象的数组FileInfo。每个对象都有不同的属性和值。仅使用$imageArray“比较”就是image123.jpgSystem.IO.FileInfo对象与String对象进行比较。FileInfoPowerShell在正确解析以查找目标值时不会自动将对象转换为字符串。

当您选择选择数组中每个对象的属性值时,您仅返回这些属性值的数组。使用$imageArray | Select -Expand Name$imageArray.Name返回属性值数组NameName在您的示例中包含一个字符串。这意味着您在使用 时将 aString与 a进行比较。String[array]::IndexOf($imageArray.Name,'image123.jpg')