微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。