我有一个包含3列和多行的CSV。每个3 x个相邻单元(每行)在单元中有多行数据,每个相邻单元的行数始终相同。
原始CSV数据:
NodeName,NodeAddress,NodeAdressDR "1.com 2.com 3.com 4.com","10.173.5.210 10.173.5.212 10.173.5.214 10.173.5.216","10.49.245.210 10.49.245.212 10.49.245.214 10.49.245.216" "5.com 6.com 7.com 8.com","10.173.5.203 10.173.5.205 10.173.5.207","10.49.245.203 10.49.245.205 10.49.245.207" ,,
这可以使用以下方法,但有一种更简单的方法可以满足每个单元的不确定数量的主机名/ IP,而无需创建单独的变量,即每行一个?
$csvImportFull = Import-CSV .\CSVFile.csv
foreach ($headingFull in $csvImportFull)
{
$nodeName = $headingFull.("NodeName")
$nodeAddress =$headingFull.("NodeAddress")
$nodeAddressDR = $headingFull.("NodeAddressDR")
$NodeName1 = ($nodeName -split "\n")[0]
$NodeName2 = ($nodeName-split "\n")[1]
$NodeName3 = ($nodeName-split "\n")[2]
$NodeName4 = ($nodeName -split "\n")[3]
$NodeAddress1 = ($nodeAddress -split "\n")[0]
$NodeAddress2 = ($nodeAddress -split "\n")[1]
$NodeAddress3 = ($nodeAddress -split "\n")[2]
$NodeAddress4 = ($nodeAddress -split "\n")[3]
$NodeAddressDR1 = ($nodeAddressDR -split "\n")[0]
$NodeAddressDR2 = ($nodeAddressDR -split "\n")[1]
$NodeAddressDR3 = ($nodeAddressDR -split "\n")[2]
$NodeAddressDR4 = ($nodeAddressDR -split "\n")[3]
write-host $NodeName1 NodeAddress1
write-host $NodeName1 NodeAddressDR1
write-host $NodeName2 NodeAddress2
write-host $NodeName1 NodeAddressDR2
}
答案 0 :(得分:1)
因此,您可以迭代分割并创建新的对象列表,而不是硬编写变量:
$objects = @()
Import-CSV .\CSVFile.csv| ForEach-Object {
$names = $_.NodeName -split '\r\n'
$address = $_.NodeAddress -split '\r\n'
$addressDr = $_.NodeAdressDR -split '\r\n'
for($i = 0; $i -le 4; $i++)
{
$objects += [PsCustomObject]@{
NodeName = $names[$i]
NodeAddress = $address[$i]
NodeAddressDr = $addressDr[$i]
}
}
}
现在您有一个对象列表,其中每个对象都有NodeName
,NodeAddress
和NodeAddressDR
所以你可以这样做:
$objects | where NodeName -eq '1.com'
输出:
NodeName NodeAddress NodeAddressDr
-------- ----------- -------------
1.com 10.173.5.210 10.49.245.210