azurepowershellazure-powershell

How do I properly use ForEach() statement of List?


I'm confused what I'm doing wrong in ForEach method syntax of List?

PS D:\ntt> $nicInfo.IpConfigurations.Count
2
PS D:\ntt> $nicInfo.IpConfigurations[0]

PrivateIpAddressVersion Name      Primary PrivateIpAddress PrivateIpAllocationMethod Subnet Name PublicIpAddress Name ProvisioningState
----------------------- ----      ------- ---------------- ------------------------- ----------- -------------------- -----------------
IPv4                    ipconfig1 True    10.233.0.4       Dynamic                                                    Succeeded


PS D:\ntt> $nicInfo.IpConfigurations.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     List`1                                   System.Object


PS D:\ntt> $nicInfo.IpConfigurations.ForEach({$_})
PS D:\ntt>

Solution

  • The problem is that PowerShell's intrinsic .ForEach() array method is preempted by the List<T> type's own .ForEach() method in this case:

    Tip of the hat to PetSerAl for providing the crucial pointers in comments.


    Workarounds:


    [1] In v5.1 of Windows PowerShell and in PowerShell (Core) 7, you can capture Write-Host output (but not Out-Host output), via the information output stream, whose number is 6, using redirection 6>&1; in the case at hand, this additionally requires enclosing the method call in (...), e.g.
    $output = ($list.ForEach({ Write-host ($args[0] + '!') })) 6>&1
    However, note that what is captured are [System.Management.Automation.InformationRecord] instances that merely contain the stringified representations of the objects passed to Write-Host, in their .MessageData.Message property.