处理值数组时,indexof
可用于查找值在数组中的位置。
#this returns '1', correctly identifying 'blue' in position '1' of the array
$valueArray = @('cup','blue','orange','bicycle')
[array]::indexof($valueArray,'blue')
我想使用此命令在使用 Get-ChildItem
生成的对象数组中查找文件(图像)的位置,但是无论如何返回的位置始终为“-1”我所要求的对象实际上在哪里。请注意,image123.jpg 位于数组的中间。
$imageArray = Get-ChildItem "C:\Images"
[array]::indexof($imageArray,'image123.jpg')
我注意到,如果我将数组更改为仅文件名,它会返回文件名的实际位置。
$imageArray = Get-ChildItem "C:\Images" | select -expand Name
[array]::indexof($imagesToReview,'image123.jpg')
这只是使用 indexof
的本质,还是有一种方法可以在不转换的情况下找到图像文件在数组中的正确位置?
最佳答案
这里最简单的解决方案如下:
$imageArray = Get-ChildItem "C:\Images"
[array]::indexof($imageArray.Name,'image123.jpg')
解释:
[array]::IndexOf(array array,System.Object value)
在 array
对象中搜索对象 value
。如果未找到匹配项,则返回 array
下界减 1。由于数组的第一个索引是 0
,因此返回 0-1< 的结果
.
Get-ChildItem -Path SomePath
返回 DirectoryInfo
和 FileInfo
对象的数组。这些对象中的每一个都有不同的属性和值。仅使用 $imageArray
与 image123.jpg
进行比较将是将 System.IO.FileInfo
对象与 String
进行比较> 对象。 PowerShell 在正确解析以查找目标值时不会自动将 FileInfo
对象转换为字符串。
当您选择选择数组中每个对象的属性值时,您返回的只是这些属性值的数组。使用 $imageArray |选择 -Expand Name
和 $imageArray.Name
返回 Name
属性值的数组。 Name
在您的示例中包含一个字符串。这意味着您在使用 [array]::IndexOf($imageArray.Name,'image123.jpg')
时将 String
与 String
进行比较>.
关于arrays - 查找对象数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61347791/