【问题标题】:Change a value in column of a CSV file更改 CSV 文件列中的值
【发布时间】:2017-06-05 16:59:43
【问题描述】:

我正在尝试找到一种方法来使用 PowerShell 更改 csv 文件中“可用人员”列中所有条目的值。

如果值为'Y',则应更改为'1',如果值为'N',则应更改为')':

分支机构编号、CoreID、可用人员、工作站
8002, FMD354800200, Y,
8002, FMD354800201, Y,
8002, FMD354800202, N,
8002, FMD354800203, N,
8002, FMD354800204, Y,

这是我尝试过的:

$csv=Import-Csv user.csv' | $csv | %{ if($_.'Available Person' -eq "Y") {$_.'Available Person'="1"} } $csv|export-csv user1.csv' -NoTypeInformation

【问题讨论】:

  • 您能否展示您尝试过的代码以及遇到问题的地方?

标签: powershell csv


【解决方案1】:

以下是一些示例代码,说明如何使用 Switch 语句解决此问题

$ImportedCSV = Import-CSV C:\user.csv
$NewCSV = Foreach ($Entry in $ImportedCsv) {
    Switch ($Entry."Available Person") {
        Y {$Entry."Available Person" = "1"}
        N {$Entry."Available Person" = ")"}
        default {Write-Error "$($Entry."Branch Number") has unexpected value for Available Person"}
    }
    $Entry
}
$NewCSV | Export-CSV C:\user1.csv -NoTypeInformation

【讨论】:

    【解决方案2】:

    试试这个

    (Import-Csv C:\temp\LastAnalyse.csv | 
        %{$_.'Available Person'=if ($_.Path -eq 'Y') {'1'} elseif ($_.Path -eq 'N') {')'} else {$_.'Available Person'}; $_}) | 
            Export-Csv  C:\temp\LastAnalyse.csv -NoTypeInformation
    

    【讨论】:

      【解决方案3】:
      $csv = Import-Csv -Path 'C:\TEMP\41768152.csv'
      
      $csv | ogv
      
      foreach ($row in $csv)
      {
          $row.'Available Person' = $row.'Available Person' -ireplace 'Y','1' -ireplace 'N',')'
      }
      
      $csv | ogv
      

      【讨论】:

      • 不起作用,如果 'Available Person' = 'PAPY IS A NOOBY' 你的解决方案替换为 'PAP1 IS A (OOB1' :)
      猜你喜欢
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2023-03-28
      • 2018-03-28
      相关资源
      最近更新 更多