Powershell,将foreach循环的输出与多个命令结合起来

Powershell, combine output of a foreach loop with multiple commands

我需要获取多个服务器的属性列表,但我在循环中遇到了第二个命令的输出:

$(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

第一个cmd的输出是正确的:

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

第二个命令似乎被忽略了... 如果我 运行 手动命令输出是正确的:

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

我做错了什么?

为了排除故障,试试这个:

$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
}

您需要将两个输出组合成一个对象。

尝试

$(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

您不需要调用 Get-NetAdapter,因为 Get-NetAdapterBinding 已经 returns 所有适配器的所有绑定。

在 foreach 循环中,您没有将 -Name 参数与 Get-NetAdapterBinding 一起使用,因此它会在循环的每次迭代中返回所有适配器的所有绑定。

您可以在 Select-Object 中使用表达式块来获得额外的双工 属性,如下所示:

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