首页 > 解决方案 > 循环遍历文件内容并使用 PowerShell 替换值

问题描述

在一个文件夹中,我有一个 CSV 文件列表,其中顶行如下所示:

高清, P00327971 ,20180816,,20180816, NoInvoice ,18990.00,0,0

注意粗体部分,第一个是采购订单,第二个是发票编号的位置。

我还有一个发票文件,其中包含每个 PO 的发票列表,我可以在 PowerShell 中将其转换为如下所示的数组:

在此处输入图像描述

在这里,您可以看到带有发票编号的 PO 列表。

我想做的是遍历每个 CSV 文件,获取第一行内容,将其中的 PO 与我创建的数组匹配,然后用发票数组中的匹配发票替换文本“NoInvoice”。

标签: powershell

解决方案


好的,我想你对此并没有更清楚,所以这里是基于一些假设的尝试:

我收集您的“发票文件列表”是一个带有标题的 csv 文件cust_poTextbox362您可以使用Import-Csv.

在这里,我将使用

$poArray = @(
    [pscustomobject]@{cust_po = 'P00328431'; Textbox362 = 5233329}
    [pscustomobject]@{cust_po = 'P00336936'; Textbox362 = 5233331}
    [pscustomobject]@{cust_po = 'P00327971'; Textbox362 = 5233332}
)

然后有一个路径,您有几个需要更新的 csv 文件。

$path = "<YOUR PATH TO THE CSV FILES>"

然后我认为这样的事情会起作用:

# read the csv files one by one as string arrays.
Get-ChildItem $path -Filter '*.csv' | ForEach-Object {
    $data = Get-Content $_.FullName
    # get the 'kinda' headers from the first row and split into array by delimiter comma
    $headers = $data[0] -split ','
    # check if these headers contain the string 'NoInvoice'
    if ($headers -contains 'NoInvoice') {
        # search array for the second value (item 1)
        $po = $poArray | Where-Object {$_.cust_po -eq $headers[1]}
        if ($po) {
            $headers[5] = $po.Textbox362   # the 6th element has the 'NoInvoice' text
            # recreate the header line
            $data[0] = $headers -join ','
            # create a new name for the updated file
            $fileDir = [System.IO.Path]::GetDirectoryName($_.FullName)
            $fileName = [System.IO.Path]::GetFileNameWithoutExtension($_.FullName) + '_updated.csv'
            $newFile = [System.IO.Path]::Combine($fileDir,$fileName)  # or use Join-Path
            Set-Content -Path $newFile -Value $data -Force
            Write-Host "File $newFile created."
        }
        else {
            Write-Warning "SKIPPED: Value $($headers[1]) not found in array for file $($_.Name)."
        }
    }
    else {
        Write-Warning "SKIPPED: File $($_.Name) does not have the 'NoInvoice' value in its header."
    }
}

推荐阅读