列的Powershell import-csv条件

时间:2016-09-13 01:13:33

标签: powershell csv import scripting

我正在尝试找到使用Powershell根据以下条件修改CSV行的最佳方法:

IF column TEST contains a WORD,WORD
THEN do the following:
 1) copy the entire row once but keep only the FIRST WORD in column TEST
 2) copy the entire row again but keep only the SECOND WORD in column TEST
 3) delete the original row that had WORD,WORD in column TEST

示例:

subject~school~TEST~code~year
math~PADF~true,false~0943~2016

我想:

subject~school~TEST~code~year
math~PADF~true~0943~2016
math~PADF~false~0943~2016

我不是Powershell的专家,但我正在使用import-csv,然后使用Get-Content Foreach对象,但它无法正常工作。如果有人知道更简单的方法或上述案例的解决方案,那就太棒了!

谢谢

1 个答案:

答案 0 :(得分:1)

  

了解更简单的方法或上述案例的解决方案

通过编程,通常没有“ ”解决方案。写下你想做的事情(你的问题中的好的步骤1,2,3),然后编写一些代码来做到这一点:

Import-Csv D:\data.csv -Delimiter '~' | ForEach-Object {

    if ($_.TEST -match ',')                  # IF row.TEST contains a comma
    {
        $first, $second = $_.TEST.Split(',') # Get first and second words ready

        $_.TEST = $first                     # Output the record once with 
        $_                                   # first word

        $_.TEST = $second                    # and again with second word
        $_                                   #
    }
    else 
    {
        $_                                   # otherwise output it unchanged
    }
} | Export-CSV out.csv -Delimiter '~' -NoTypeInformation

不完全确定删除是什么意思,但你可以运行它和Export-CSV out.csv -Delimiter '~' -NoTypeInformation并输出到没有原始WORD,WORD行的新文件。