March 4, 2016

PowerShell 4.0 GetEnumerator not working if array variable name length > 20 chars

Problem

Was going about my daily PowerShell (4.0) life and run into issue where the following script didn’t output any rows.

$moduleSiteCollections = @{
    'Field Intelligence' = 'fi';
    'News Feeds' = 'nf';
    'Key Developments' = 'kd'
}
foreach ($sitecoll in $moduleSiteCollections.GetEnumerator()) {   
    Write-Host $($sitecoll.Value)
}

Solution

If the length of the name of the variable holding the array is longer than 20 characters, GetEnumerator won’t return any results, so reduce variable name to 20 characters or less. Or use PowerShell 5.0.

The following script works fine.

$moduleSiteCollection = @{
    'Field Intelligence' = 'fi';
    'News Feeds' = 'nf';
    'Key Developments' = 'kd'
}
foreach ($sitecoll in $moduleSiteCollection.GetEnumerator()) {   
    Write-Host $($sitecoll.Value)
}

No comments:

Post a Comment