首页 > 解决方案 > 问题错误检查 - 匹配和 IF 语句

问题描述

下面的脚本将从我们的 MIS 系统导入导出的 CSV,以便我们可以上传到谷歌课堂。在 tern 中,这将允许基于 regex.csv 中的单词匹配使用我们的自定义类名批量创建类。

从exporteddata.csv 可以看出,10552 为空白。

是否可以将其从最终导出中省略并添加到其自己的 errors.csv 文件中?

任何帮助都会很棒!

脚本.ps1

$data = Import-Csv "$PSScriptRoot\data.csv" -Delimiter ','
$patterns = Import-Csv "$PSScriptRoot\Regex\regex.csv" -Delimiter ','
$interimexportedData = "$PSScriptRoot\classesinterim.csv" 
$exportclasses = "$PSScriptRoot\exporteddata.csv" 

## Imports the initial SIMS export of classes and created a 'prefered' name for the class, then exports to a CSV.
$data | Select-Object *,@{Name='preference'; Expression={
  foreach ($p in $patterns) {
    if ($_.title -match $p.'regex_key') {
     $p.preference + " " + "-" + " " + $_.title
     return
    }
  }    
}  

} | Select-Object -property sourcedID, preference | Export-Csv $interimexportedData -NoTypeInformation

## The below re-imports the csv file and renames the header
Import-Csv $interimexportedData |
Select-Object -property sourcedID, @{ expression={$_.preference}; label='title' } |
Export-Csv -NoTypeInformation $exportclasses

## Delete the classesinterim.csv from the folder
Remove-Item $interimexportedData

数据.csv

"sourcedId","title"
9443,"10A/BS1"
9444,"10A/FR1"
10598,"10A/Ft"
9445,"10A/GG1"
9446,"10A/HI1"
9447,"10A/ME1"
9451,"10A/ME2"
9448,"10A/RM1"
9449,"10A/SCTrX"
9452,"10A/SCTrY"
10552,"10A/SOS"
9450,"10A/SP1"

导出数据.csv

"sourcedId","title"
"9443","Business Studies - 10A/BS1"
"9444","French - 10A/FR1"
"10598","Form Time - 10A/Ft"
"9445","Geography - 10A/GG1"
"9446","History - 10A/HI1"
"9447","Media Studies - 10A/ME1"
"9451","Media Studies - 10A/ME2"
"9448","Resistant Materials - 10A/RM1"
"9449","Science - 10A/SCTrX"
"9452","Science - 10A/SCTrY"
"10552",""

正则表达式.csv

"regex_key","preference"
BS,"Business Studies"
FR, "French"
Ar,"Art"
Bt,"Eng & Maths Booster"
Bs,"Business"
Cn,"Construction"
Co,"Computing"

标签: powershellcsv

解决方案


用于Where-Object过滤掉具有空白值的对象:

$data | Select-Object *,@{Name='preference'; Expression={
  foreach ($p in $patterns) {
    if ($_.title -match $p.'regex_key') {
     $p.preference + " " + "-" + " " + $_.title
     return
    }
  }    
} |Where-Object preference -ne ''

推荐阅读