1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
$rawCsv = @" EmployeeID,Name,Department,Salary,HireDate,Status E001,张三,技术部,15000.50,2020-03-15,Active E002,李四,市场部,,2021-07-20,Active E003,王五,技术部,18000,2022-01-10,Inactive E004,,财务部,12000,2023/06/01,Active E005,赵六,技术部,20000.99,invalid,Active E006,钱七,,16500,2020-11-30,Active "@
function Import-AndCleanCsv { param( [Parameter(Mandatory)] [string[]]$CsvLines,
[string]$DefaultDepartment = "未分配",
[decimal]$DefaultSalary = 0 )
$data = $CsvLines | ConvertFrom-Csv
$cleaned = foreach ($row in $data) { $name = if ([string]::IsNullOrWhiteSpace($row.Name)) { "未知员工($($row.EmployeeID))" } else { $row.Name.Trim() }
$dept = if ([string]::IsNullOrWhiteSpace($row.Department)) { $DefaultDepartment } else { $row.Department.Trim() }
$salary = if ($row.Salary -match '^\d+\.?\d*$') { [decimal]$row.Salary } else { $DefaultSalary }
$hireDate = $null if ($row.HireDate -match '^\d{4}-\d{2}-\d{2}$') { $hireDate = [datetime]::ParseExact($row.HireDate, "yyyy-MM-dd", $null) } elseif ($row.HireDate -match '^\d{4}/\d{2}/\d{2}$') { $hireDate = [datetime]::ParseExact($row.HireDate, "yyyy/MM/dd", $null) }
[PSCustomObject]@{ EmployeeID = $row.EmployeeID Name = $name Department = $dept Salary = $salary HireDate = if ($hireDate) { $hireDate.ToString("yyyy-MM-dd") } else { "N/A" } Status = $row.Status Cleaned = $true } }
return $cleaned }
$cleanData = Import-AndCleanCsv -CsvLines ($rawCsv -split "`n") $cleanData | Format-Table -AutoSize
|