Powershell:写入 CSV 的嵌入式哈希表

Powershell: Embedded Hashtable writing to CSV

目前正在尝试将哈希表写入 CSV 文件。我要找的格式是

IP Ports
IP Port
Port
Port
IP Port
Port
Port

我在执行此操作时遇到了两个问题。

1.)

IP Ports
IP System.Collections.DictionaryEntry System.Collections.DictionaryEntry etc...
IP System.Collections.DictionaryEntry System.Collections.DictionaryEntry etc...
IP System.Collections.DictionaryEntry System.Collections.DictionaryEntry etc...
IP System.Collections.DictionaryEntry System.Collections.DictionaryEntry etc...

2.)

#TYPE System.Management.Automation.PSCustomObject
IP IP IP IP IP
@{Port=; Port=; Port=;....} @{Port=; Port=; Port=;...} @{Port=; Port=; Port=;...} @{Port=; Port=; Port=;...} @{Port=; Port=; Port=;...}

下面是代码

$filepath = "ip.csv"
$host_list = Import-Csv $filepath

$hash = @{}
$host_list | ForEach-Object{
    if($hash.ContainsKey($_.IP)){
            $IP = $_.IP
            if($hash.$IP.ContainsKey($_.Port)){
            }
            else{
                $Port = $_.Port
                $hash.$IP.$Port = @{}
            }
    }
    else{
        $IP = $_.IP
        $hash.$IP = @{}
    }
}

##Gives Table 1 Csv output
ForEach-Object{$hash.GetEnumerator() | sort Name} |
   Select-Object -Property @{N='IP'; E ={$_.Key}}, @{N='Port'; E={$_.Value.GetEnumerator()}}|
   Export-Csv -NoTypeInformation -Path "IPList.csv"

##Gives Table 2 csv output 

$HashObj = New-Object -TypeName PSObject -Property $hash
$HashObj | ConvertTo-Json |Set-Content -Path "IPList.json"

Get-Content IPList.json | ConvertFrom-Json | Export-Csv PlzWork.csv 


您想要的 CSV 输出格式不常见,因为行不是独立的:

听起来你想要一个空的 IP 列来暗示该行的 Port 列值与最近一行的 IP 值相关联IP 列值。

要获得所描述的格式,请尝试以下操作(要切换到正常的独立行格式,请删除 $ip = $null 语句):

$hash.GetEnumerator() | Sort-Object Name | ForEach-Object { 
  $ip = $_.Name
  foreach ($port in $_.Value.Keys) { 
    [pscustomobject] @{ IP = $ip; Port = $port } # construct and output an object
    $ip = $null 
  }
} | Export-Csv -NoTypeInformation IPList.cs
  • 要在导出前以表格形式查看生成的对象,请省略 | Export-Csv ... 调用。

  • 要将结果CSV数据输出为strings,默认显示,将| Export-Csv ...替换为| ConvertTo-Csv