遍历CSV,根据条件和表达式编辑字段

时间:2018-10-26 18:11:52

标签: powershell

我正在尝试导入CSV并遍历它,根据一些数学+条件为字段设置一个新值。这是我到目前为止的内容:

import-csv "$folder\test2.csv" | ForEach-Object {
  if ($_.SubmissionID -ne "" -and $_.SubmissionID -ne "SubmissionID"){
    echo $_
    $totaldocs = $_.TotalDocs
    $addnpages = $_.AddnPages
    if ($_.SubmitterName -match "check|Check"){
    echo "YES"
    $_.Cost = ([int]$totaldocs * .09)
    }
    if ($_.SubmitterName -notmatch "check|Check"){
    echo "NO"
    $_.Cost = (([int]$totaldocs + [int]$addnpages) * .05)
    }
    echo $_.Cost
  }
} |
export-csv "$folder\test3.csv" -NoTypeInformation

调试该块,我可以看到正在设置“ Cost”字段,但是,当它导出最终的CSV时,更改不会保留。不仅如此,每行之间还有其他空白行。

有什么我想念的吗?如果有更好的方法,我愿意提出建议。

1 个答案:

答案 0 :(得分:1)

如果您输入的CSV文件如下所示:

"SubmissionID","SubmitterName","TotalDocs","AddnPages","Cost"
"abcdef", "Check", "12", "3", "5"
"ghijkl", "check", "10", "7", "25"

下面的代码将满足您的要求(如果我正确理解了这个问题)

Import-Csv "$folder\test2.csv" | ForEach-Object {
  if (!([string]::IsNullOrEmpty($_.SubmissionID)) -and $_.SubmissionID -ne "SubmissionID"){
    $totaldocs = $_.TotalDocs
    $addnpages = $_.AddnPages
    if ($_.SubmitterName -match "check") {  # -match is case-insensitive
        $_.Cost = ([int]$totaldocs * .09)
    }
    else {
        $_.Cost = (([int]$totaldocs + [int]$addnpages) * .05)
    }
    ###############################################################
    # output the result. This is what you forgot in the original code
    ###############################################################
    $_
  }
} | Export-Csv "$folder\test3.csv" -NoTypeInformation

输出:

"SubmissionID","SubmitterName","TotalDocs","AddnPages","Cost"
"abcdef","Check","12","3","1.08"
"ghijkl","check","10","7","0.9"

编辑

LotPings的观察很好:

上面的代码将跳过未通过测试的行:

if (!([string]::IsNullOrEmpty($_.SubmissionID)) -and $_.SubmissionID -ne "SubmissionID")

如果您还希望这些行也包含在输出文件中,则将(输出的)$_下移一级。然后,代码变为:

Import-Csv "$folder\test2.csv" | ForEach-Object {
  if (!([string]::IsNullOrEmpty($_.SubmissionID)) -and $_.SubmissionID -ne "SubmissionID"){
    $totaldocs = $_.TotalDocs
    $addnpages = $_.AddnPages
    if ($_.SubmitterName -match "check") {  # -match is case-insensitive
        $_.Cost = ([int]$totaldocs * .09)
    }
    else {
        $_.Cost = (([int]$totaldocs + [int]$addnpages) * .05)
    }
  }
  ###############################################################
  # output the result, changed or not.
  ###############################################################
  $_
} | Export-Csv "$folder\test3.csv" -NoTypeInformation