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

问题描述

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

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

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

Get-NetAdapteradvancedProperty "LAN_Clients" -displayName "Speed & Duplex" | select displayValue
    
displayValue
------------
Auto Negotiation

我做错了什么?

解决方法

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

试试

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

出于故障排除目的,请尝试以下操作:

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

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

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

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

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