ilRobby
ilRobby

Reputation: 113

Powershell, combine output of a foreach loop with multiple commands

I need to get a list of properties for multiple server, but I'm stuck with the output of second command in my loop:

$(foreach ( $Net in $Nets ) {
Get-NetAdapterBinding -ComponentID  ms_msclient,ms_server,ms_tcpip6 -ErrorAction SilentlyContinue | select Name,DisplayName,Enabled
Get-NetAdapterAdvancedProperty $Net -DisplayName "Speed & Duplex" | select DisplayValue
}) | Format-List

The output of first cmd is correct:

Name        : LAN_Clients
DisplayName : Internet Protocol Version 6 (TCP/IPV6)
Enabled     : False

Name        : LAN_Clients
DisplayName : File and Print Sharing
Enabled     : False

Name        : LAN_Clients
DisplayName : Client for Microsoft Networks
Enabled     : False

The second cmd seems ignored... If I run cmd manually the output is correct:

Get-NetAdapterAdvancedProperty "LAN_Clients" -DisplayName "Speed & Duplex" | select DisplayValue
    
DisplayValue
------------
Auto Negotiation

What am I doing wrong?

Upvotes: 2

Views: 4324

Answers (3)

antonyoni
antonyoni

Reputation: 909

You don't need to call Get-NetAdapter, as Get-NetAdapterBinding already returns all the bindings for all the adapters.

In the foreach loop, you're not using the -Name parameter with Get-NetAdapterBinding so it's returning all the bindings for all your adapters every iteration of the loop.

You can use an expression block in Select-Object to get the additional duplex property you're after, like this:

Get-NetAdapterBinding -ComponentID  ms_msclient,ms_server,ms_tcpip6 -ErrorAction SilentlyContinue |
    Select-Object Name,DisplayName,Enabled, @{Name = 'Speed & Duplex'; Expression={Get-NetAdapterAdvancedProperty -InterfaceAlias $_.InterfaceAlias -DisplayName 'Speed & Duplex' | select -ExpandProperty DisplayValue }} |
    Format-List

Upvotes: 0

Theo
Theo

Reputation: 61243

You need to combine both outputs into a single object.

Try

$(foreach ( $Net in $Nets ) {
    $speed = (Get-NetAdapterAdvancedProperty $Net -DisplayName "Speed & Duplex").DisplayValue
    Get-NetAdapterBinding -ComponentID  ms_msclient,ms_server,ms_tcpip6 -ErrorAction SilentlyContinue |   
    Select-Object Name,DisplayName,Enabled,
                  @{Name = 'Speed & Duplex'; Expression = {$speed}}
}) | Format-List

Upvotes: 1

Abraham Zinala
Abraham Zinala

Reputation: 4694

For troubleshooting purposes, try this:

$Nets = Get-NetAdapterBinding -ComponentID  ms_msclient,ms_server,ms_tcpip6 -ErrorAction SilentlyContinue
    foreach ($Net in $Nets.name ) {
Get-NetAdapterAdvancedProperty $Net -DisplayName "Speed & Duplex" | select DisplayValue
}

Upvotes: 0

Related Questions