方法调用失败,因为System.Object[]]在PowerShell中不包含方法名indexOf

方法调用失败,因为System.Object[]]在PowerShell中不包含方法名indexOf,powershell,Powershell,尝试运行以下powershell脚本时出现错误IndexOf。有什么建议吗 $unlicensedUsers = Get-MsolUser -UnlicensedUsersOnly foreach ($aUser in $unlicensedUsers) { if ($unlicensedUsers.IndexOf($aUser) % 10 -eq 0) { Write-Host -ForegroundColor yellow $unlicensedUsers.In

尝试运行以下powershell脚本时出现错误IndexOf。有什么建议吗

$unlicensedUsers = Get-MsolUser -UnlicensedUsersOnly
foreach ($aUser in $unlicensedUsers)
{
   if ($unlicensedUsers.IndexOf($aUser) % 10 -eq 0) {
            Write-Host -ForegroundColor yellow $unlicensedUsers.IndexOf($aUser)
   }
}
错误:

IndexOf:方法调用失败,因为System.Object[]不包含方法名IndexOf

IndexOf()
列表
类型上的一个方法,通常不在PowerShell中使用。大多数情况下,您在
foreach
中使用的变量将是对象数组(如示例中所示)或其他类型的集合。对象数组没有等效的方法,因此您必须保存自己的数组索引副本:

$unlicensedUsers = Get-MsolUser -UnlicensedUsersOnly
for ($i = 0; $i -lt $unlicensedUsers.count; $i++)
{
    if ($i % 10 -eq 0) {
        Write-Host -ForegroundColor yellow $i
    }
}
包含正确的解决方案,但解释不正确:

System.Array
实例通过接口方法的显式实现具有
.IndexOf()
方法

直到PSv2,这样的显式接口实现根本无法访问

在PSv3+中,显式接口实现可以直接在实现类型上使用,而不需要引用接口,因此您的代码可以工作,但Nacht的答案仍然是本案例中更好的解决方案


也就是说,即使在PSv2中,
[System.Array]
类型也有一个,可以按如下方式调用:

[array]::IndexOf($unlicensedUsers, $aUser) # return index of $aUser in array $unlicensedUsers

有一种静态方法,但在这种情况下,
for
循环肯定是更好的方法。确实,解决方案是正确的,但解释是错误的:Cmdlet输出由PowerShell收集在
[object[]
数组中,这样的
系统.Array
实例实现
.IndexOf()
通过显式接口实现
IList.IndexOf()
,PSv2不会出现,但PSv3+会出现。