脚本输出显示额外的逗号

时间:2017-10-12 11:21:05

标签: powershell

我有一个脚本,其中脚本检查NIC绑定顺序。

$result = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
    function Get-BindOrder {
        $Binding = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage").Bind
        $Return = New-Object PSobject
        $BindingOrder = @()
        foreach ($Bind in $Binding) {
            $DeviceId = $Bind.Split("\")[2]
            $Adapter = (Get-WmiObject Win32_Networkadapter | Where {$_.GUID -eq $DeviceId }).NetConnectionId
            $BindingOrder += $Adapter
        }
        $BindingOrder
    } #EndFunction
    CLS
    Get-BindOrder
}

$adapteresult = $result -join (",")

当我回复此$adapteresult = $result时,我得到的输出如下

PS C:\> $adapteresult
vEthernet (10.211.14.0_20)
storage
Ethernet 5
Ethernet 4
Ethernet 2
Ethernet 6

当我添加$adapteresult = $result -join (",")时,同样的变量,我将在中间添加额外的命令。

vEthernet (10.241.24.0_21),storage,Ethernet 5,,Ethernet 4,Ethernet 2,Ethernet 6,,

我不希望输出中有任何额外的逗号。期待如下输出:

vEthernet (10.241.24.0_21),storage,Ethernet 5,Ethernet 4,Ethernet 2,Ethernet 6,

2 个答案:

答案 0 :(得分:2)

(Get-WmiObject Win32_Networkadapter | Where {$_.GUID -eq $guid}).NetConnectionId似乎正在返回您在$BindingOrder中捕获的$ null。显示在屏幕上它们不占用空间,但它们无论如何都在那里。在我的机器上本地运行代码的精简版...

$results = ((Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage").Bind | Foreach-Object {
    $guid = $_.split("\")[2]
    (Get-WmiObject Win32_Networkadapter | Where {$_.GUID -eq $guid}).NetConnectionId
}) 

使用它可以查看$results

$results
$results.Count
$results -contains $null

Local Area Connection
6
True

在我的机器上,我只有一个匹配的局域连接。但是$results已存储了6个项目,其中至少有一个是$null。您需要过滤掉查询中出现的这些结果。

 $Adapter = (Get-WmiObject Win32_Networkadapter | Where {$_.GUID -eq $DeviceId }).NetConnectionId
 if($Adapter){
     $BindingOrder += $Adapter
 }

应该这样做。如果$adapter为空或空字符串,则不会将其添加到$bindingorder

答案 1 :(得分:0)

我已经纠正了自己,现在工作正常

  $a = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage").Bind | ForEach-Object {
          $guid = ($_ -split '\\')[2]
          Get-WmiObject -Query "SELECT * FROM Win32_NetworkAdapter WHERE GUID='$guid'" |
            Select-Object -ExpandProperty NetConnectionID
        }

$b = $a -join","