比较数组与foreach循环

时间:2020-07-27 11:42:40

标签: powershell indexof

我正在尝试查看数组中是否存在值。当我手动输入字符串时,函数的索引有效。但是,当我使用foreach循环的值不起作用时,我在做什么错呢? (有关更多信息,请参见图片)

                $groups = Get-ADGroup -Filter { GroupCategory -eq "Security" -and GroupScope -eq "Global"  } -Properties isCriticalSystemObject | Where-Object { !($_.IsCriticalSystemObject) -and !($_.Name -eq "DnsUpdateProxy") }
                
            $currentFlexAssets = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $api__flex_asset_id -filter_organization_id $api__org_id )                
            
            
            # Delete groups from IT Glue that no longer exist in AD
            $api__flex_asset_id = ''
            Foreach ($asset in $currentFlexAssets.data.attributes.name) {
                        
                $asset
                
                $fa_index = [array]::indexof($groups.Name ,'$asset')
            
                $fa_index
                                    
                #if($fa_index -eq '-1') {
                #   Write-Host "Destroy = " $asset 
                #}
            }

powershell console

1 个答案:

答案 0 :(得分:1)

正如Mathias所言,您不应在$asset变量周围使用单引号。通过使用单引号,IndexOf将与文字值“ $ asset”进行比较,而不是与该变量包含的内容进行比较。

如果找不到IndexOf()方法,则为您提供-1 int 值,或者您要查找的字符串的实际数组索引。 但是,请注意IndexOf区分大小写,因此可能找不到您想要的内容。

要使其不区分大小写,您可以执行以下操作:

$groups = Get-ADGroup -Filter "GroupCategory -eq 'Security' -and GroupScope -eq 'Global'" -Properties isCriticalSystemObject | 
          Where-Object { !($_.IsCriticalSystemObject) -and !($_.Name -eq "DnsUpdateProxy") }

$currentFlexAssets = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $api__flex_asset_id -filter_organization_id $api__org_id )

# make all items in the array lowercase for the IndexOf() method
$groupsNames = $groups.Name | ForEach-Object { $_.ToLower() }

然后,在您的foreach ($asset in $currentFlexAssets.data.attributes.name)循环中执行以下操作:

$fa_index = [array]::IndexOf($groupsNames, $asset.ToLower())
if($fa_index -lt 0) {   # IndexOf() returns an int, so son't quote here
     Write-Host "Destroy = $asset"
}