PowerShell 合并来自多个 CSV 的数据
PowerShell merging data from multiple CSVs
我有一堆 CSV 文件,其中包含有关 DHCP 范围的信息(100 多个文件,每个服务器一个)。我希望将所有数据合并到一个新的 table 中。有一些方法可以合并 CSV,但这还不够好,因为最重要的信息之一没有包含在单个 CSV 文件中……服务器名称。服务器名称来自文件名本身。因此,构建新 table.
的方法
我的问题是 SubnetMask、StartRange、EndRange、ScopeID 和 State 的属性正在同一个“单元格”中输出。我设法为 ScopeName 做到了(即设法每行获得一个 ScopeName),但不确定如何处理其余部分。
$outputTable = $null
$files = Get-ChildItem -Path "C:\Temp\Discovery\" -Filter *Scopes.csv
Write-Host $files
ForEach($file in $files)
{
$scopeFile = Import-Csv $file
ForEach ($scopeName in $scopeFile.Name)
{
$outputTable += @(
[pscustomobject]@{
` DHCPServer=$file.Name.ToString().Split(".")[0];
` ScopeName=$scopeName;
` SubnetMask=$scopeFile.SubnetMask;
` StartRange=$scopeFile.StartRange;
` EndRange=$scopeFile.EndRange;
` ScopeID=$scopeFile.ScopeID
` State=$scopeFile.State
}
)
}
}
$outputTable | ft
当前输出:
预期输出:
DHCPServerName,ScopeName,SubnetMask,StartRange,EndRange,ScopeID,State
server1,london,255.255.0.0,192.168.0.1,192.168.0.254,192.168.0.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,NotActive
您可以使用 calculated property with Select-Object
添加文件的 Name
作为 Csv 的新列:
$merged = foreach($file in Get-ChildItem -Path C:\Temp\Discovery\ -Filter *Scopes.csv)
{
Import-Csv $file.FullName | Select-Object @{
Name = 'DHCPServerName'
Expression = { $file.Name.Split(".")[0] }
}, *
}
$merged | Format-Table
我有一堆 CSV 文件,其中包含有关 DHCP 范围的信息(100 多个文件,每个服务器一个)。我希望将所有数据合并到一个新的 table 中。有一些方法可以合并 CSV,但这还不够好,因为最重要的信息之一没有包含在单个 CSV 文件中……服务器名称。服务器名称来自文件名本身。因此,构建新 table.
的方法我的问题是 SubnetMask、StartRange、EndRange、ScopeID 和 State 的属性正在同一个“单元格”中输出。我设法为 ScopeName 做到了(即设法每行获得一个 ScopeName),但不确定如何处理其余部分。
$outputTable = $null
$files = Get-ChildItem -Path "C:\Temp\Discovery\" -Filter *Scopes.csv
Write-Host $files
ForEach($file in $files)
{
$scopeFile = Import-Csv $file
ForEach ($scopeName in $scopeFile.Name)
{
$outputTable += @(
[pscustomobject]@{
` DHCPServer=$file.Name.ToString().Split(".")[0];
` ScopeName=$scopeName;
` SubnetMask=$scopeFile.SubnetMask;
` StartRange=$scopeFile.StartRange;
` EndRange=$scopeFile.EndRange;
` ScopeID=$scopeFile.ScopeID
` State=$scopeFile.State
}
)
}
}
$outputTable | ft
当前输出:
预期输出:
DHCPServerName,ScopeName,SubnetMask,StartRange,EndRange,ScopeID,State
server1,london,255.255.0.0,192.168.0.1,192.168.0.254,192.168.0.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,NotActive
您可以使用 calculated property with Select-Object
添加文件的 Name
作为 Csv 的新列:
$merged = foreach($file in Get-ChildItem -Path C:\Temp\Discovery\ -Filter *Scopes.csv)
{
Import-Csv $file.FullName | Select-Object @{
Name = 'DHCPServerName'
Expression = { $file.Name.Split(".")[0] }
}, *
}
$merged | Format-Table