目前正在嘗試將 Hashtable 寫入 CSV 檔案。我正在尋找的格式是
| 知識產權 | 埠 |
|---|---|
| 知識產權 | 港口 |
| 港口 | |
| 港口 | |
| 知識產權 | 港口 |
| 港口 | |
| 港口 |
在執行此操作時,我遇到了兩個問題。
1.)
| 知識產權 | 埠 |
|---|---|
| 知識產權 | System.Collections.DictionaryEntry System.Collections.DictionaryEntry 等... |
| 知識產權 | System.Collections.DictionaryEntry System.Collections.DictionaryEntry 等... |
| 知識產權 | System.Collections.DictionaryEntry System.Collections.DictionaryEntry 等... |
| 知識產權 | System.Collections.DictionaryEntry System.Collections.DictionaryEntry 等... |
2.)
| #TYPE System.Management.Automation.PSCustomObject | ||||
|---|---|---|---|---|
| 知識產權 | 知識產權 | 知識產權 | 知識產權 | 知識產權 |
| @{埠=; 埠=; 埠=;....} | @{埠=; 埠=; 埠=;...} | @{埠=; 埠=; 埠=;...} | @{埠=; 埠=; 埠=;...} | @{埠=; 埠=; 埠=;...} |
下面是代碼
$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
uj5u.com熱心網友回復:
您想要的 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 資料輸出為字串,默認情況下顯示,替換
| Export-Csv ...為|ConvertTo-Csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/334682.html
