导入一个文件,操作数据并写入另一个文件

时间:2016-11-13 21:41:03

标签: powershell csv

使用PowerShell需要读取CSV文件,在某些字段上执行操作,并且只将特定字段输出到新文件。

如何在PS中实现这一目标?

为了保持尽可能简单和最小化,将CSV写入固定长度的文件,因此在此示例中,PCode的前缀为" 00"。

列的实际实现将用零,空格填充,然后每列将被修剪为只有指定数量的字符宽。

InFile.csv

ClientNumber,AccountNumber,PCode,Amount
c10,a000000001,p1,100.01
c11,a000000002,p2,200.02

OutFile.csv

ClientNumber,AccountNumber,PCode,Amount
c10a00000000100p1100.01
c11a0000000000p2200.02
$InFile  = "C:\InFile.csv"
$OutFile = "C:\OutFile.csv"

$InCSV = Import-Csv $InFile -Header "ClientNumber","AccountNumber","ZCode","Amount" |
         ConvertTo-Csv -NoTypeInformation  

foreach ($record in $CSV) {
    # left pad with zeroes
    $RR = "000" + $record.RRCode
    # write $RR to file
} 

#$CSV | Out-File $OutFile -Force -Encoding Ascii

1 个答案:

答案 0 :(得分:0)

这对我有用,字段值是左键,然后是右键" n"用于输出:

$Space = (" " * 100)
$Zero = ("0" * 100)

#ClientNumber,AccountNumber,PCode,Amount

$x = 1

Import-Csv $InFile | ForEach-Object {
    $ClientNumber  = $Space + $_.ClientNumber
    $ClientNumber1 = ($ClientNumber.Substring($ClientNumber.Length - 3, 3))

    $AccountNumber  = $Zero + $_.AccountNumber
    $AccountNumber1 = ($AccountNumber.Substring($AccountNumber.Length - 10, 10))

    $PCode  = $Space + $_.PCode
    $PCode1 = ($PCode.Substring($PCode.Length - 3, 3))

    $Amount  = $Space + $_.Amount
    $Amount1 = ($Amount.Substring($Amount.Length - 10, 10))

    New-Object -Type PSObject -Property @{
        FixedWidth = $ClientNumber1 + $AccountNumber1 + $PCode1 + $Amount1   
    }
    $x++
} | ConvertTo-Csv -NoType | ForEach-Object {
    $_ -replace '"', ''
} | Set-Content $OutFile

Invoke-Item $OutFile