More on Foreach

My post on foreach seems to haver generated a bit of confusion. I was trying to use the calculations as examples not a statement that you should do things that way – there were statements to that effect in the post but they seem to have been missed.

Any way, to try and resolve the confusion here’s another couple of examples. This time getting network adapters and finding the matching IP address.

First using Foreach-Object on a pipeline

Get-CimInstance -ClassName Win32_NetworkAdapter -Filter "NetEnabled = $true" |
ForEach-Object {
  $ip = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "Index = $($psitem.DeviceId)"
  $props = @{
    Name = $psitem.NetConnectionId
    Product = $psitem.ProductName
    DHCP = $ip.DHCPEnabled
    IP   = $ip.IPAddress 
  }
  New-Object -TypeName PSObject -Property $props
} | Format-List

You can’t pipe Get-CimInstance into another call to the same cmdlet so you need to solve the problem using foreach.

Now the same problem solved using a foreach loop

$nics = Get-CimInstance -ClassName Win32_NetworkAdapter -Filter "NetEnabled = $true"
$data = foreach ($nic in $nics) {
  $ip = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter "Index = $($nic.DeviceId)"
  $props = @{
    Name = $nic.NetConnectionId
    Product = $nic.ProductName
    DHCP = $ip.DHCPEnabled
    IP   = $ip.IPAddress 
  }
  New-Object -TypeName PSObject -Property $props
} 
$data |Format-List
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s