我需要导入许多CSV文件,根据标题行值动态创建变量名,将列值分配给列数组,将唯一列值分配给唯一列数组。
ID;PlayGolf;Day;Temperature;Outlook;Humidity;Windy;
1;no;05-Jul;hot;sunny;high;FALSE;
2;no;06-Jul;hot;sunny;high;TRUE;
3;yes;07-Jul;hot;overcast;high;FALSE;
4;yes;09-Jul;cool;rain;normal;FALSE;
5;yes;10-Jul;cool;overcast;normal;TRUE;
6;no;12-Jul;mild;sunny;high;FALSE;
7;yes;14-Jul;cool;sunny;normal;FALSE;
8;yes;15-Jul;mild;rain;normal;FALSE;
9;yes;20-Jul;mild;sunny;normal;TRUE;
10;yes;21-Jul;mild;overcast;high;TRUE;
11;yes;22-Jul;hot;overcast;normal;FALSE;
例如,在上面的CSV文件中,我将创建
$ID
,则,
$PlayGolf
等等阵列
$PlayGolf
将包含值
@("no", "no", "yes", "yes",..."yes")
和数组
$PlayGolfUnique
将包含值
@("no", "yes")
。
以下片段概述了我在解决方案方面取得的进展:
Param(
[Parameter(Position = 0, HelpMessage = "Input data: (e.g. Input.csv")]
[string]$inputFile = "Input.csv",
[Parameter(Position = 2, HelpMessage = "Data delimiter: (e.g. ;")]
[string]$dataDelimiter = ";"
)
$main = {
Begin {
Write-Host "SO Question Begin..." -ForegroundColor Black -BackgroundColor Green
}
Process {
try {
$line = (Get-Content $inputFile -TotalCount 2)[0]
$delimiterCount = ([char[]]$line -eq $dataDelimiter).Count
$colHeaders = @(((Get-Content $inputFile)[0..($delimiterCount - 1)] -split ($dataDelimiter))[0..($delimiterCount - 1)])
} catch {
Write-Host "Error: $($_.Exception)" -ForegroundColor White -BackgroundColor Red
Break
}
}
End {
if ($?) {
Write-Host "Completed Successfully." -ForegroundColor Black -BackgroundColor Green
Write-Host "SO Question End..." -ForegroundColor Black -BackgroundColor Green
}
}
}
& $main