【问题标题】:Powershell5 IndexOf behaviour changed - suggestions?Powershell IndexOf 行为已更改 - 建议?
【发布时间】:2016-04-14 09:33:15
【问题描述】:

最近将我的工作站升级到 Windows10,我一直在检查我所有的旧脚本,似乎 IndexOf 的行为有所不同。

在 PS4 中这很好用:

    $fullarray = $permissions | %{
    $obj = new-object psobject
    $obj | add-member -name Group -type noteproperty -value $_.Account.AccountName
    $obj | add-member -name Access -type noteproperty -value $_.AccessRights
    $obj
}   
$array = {$fullarray}.Invoke()
# Convert array to list from which we can remove items
$arraylist = [System.Collections.ArrayList]$array
# Remove admin groups/users
$ExcludeList | % {
    $index = ($arraylist.group).IndexOf($_)
    If ($index -gt -1) {
        $arraylist.RemoveAt($index) | Out-Null
    }
}

但是在 PS5 中,IndexOf 只为所有值返回 -1。我根本找不到一种方法让它与 arraylists 一起工作 - 现在我有这个 kludge 修复让它在 PS5 中工作:

    $array = {$fullarray}.Invoke()
# Convert array to list from which we can remove items
$arraylist = [Collections.Generic.List[Object]]($array)
# Remove admin groups/users
ForEach ($HideGroup in $ExcludeList) {
    $index = $arraylist.FindIndex( {$args[0].Group -eq $HideGroup} )
    If ($index -gt -1) {
        $arraylist.RemoveAt($index) # | Out-Null
    }
}

任何关于为什么会发生变化的想法,如果您有更好的解决方案,将不胜感激!

【问题讨论】:

    标签: powershell indexof powershell-4.0 powershell-5.0


    【解决方案1】:

    我不知道为什么你会看到 ArrayList.IndexOf() 的不同行为的答案,但我建议使用 Where-Object 而不是你正在做的事情:

    $fullarray = $permissions | ForEach-Object {
        $obj = new-object psobject
        $obj | add-member -name Group -type noteproperty -value $_.Account.AccountName
        $obj | add-member -name Access -type noteproperty -value $_.AccessRights
        $obj
    } 
    $filteredarray = $fullarray | Where-Object { $Excludelist -notcontains $_.Group }
    

    【讨论】:

    • 好声音。该脚本一直在发展,我想我最初更改为 ArrayList 因为我还想根据其他标准(例如,如果用户已经是成员)删除并在删除不需要的组后添加一个项目,但我可以看到使用这种方法可能仍然更简单。谢谢
    • 你也可以使用Where-Object 来做到这一点
    猜你喜欢
    • 2022-12-23
    • 1970-01-01
    • 2022-01-14
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多