循环浏览文件内容并用PowerShell替换值

时间:2018-08-21 12:58:05

标签: powershell

在一个文件夹中,我有一个CSV文件列表,其中第一行看起来像这样:

HD,P00327971,20180816,,20180816,NoInvoice,18990.00,0,0

请注意加粗的部分,第一个是采购订单,第二个是发票编号所在的地方。

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

enter image description here

在这里您可以看到带有每个发票编号的采购订单列表。

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

2 个答案:

答案 0 :(得分:0)

好吧,我想您对此没有什么更清楚的了解,因此,请根据以下几个假设进行尝试:

我收集的“发票清单文件”是一个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."
    }
}

答案 1 :(得分:0)

我认为在文件名中查找PO而不是尝试处理每个文件的内容会更容易,因此我将输出设置为将PO包含在文件名中,发现找到解决方案要容易得多

下面是我想出的代码:

struct wifiConn {
  char eSsid[32];
  char ePasw[32];
};

void write_wifi_toEEPROM(uint8_t startAddr, String strSSID, String strPW){
  wifiConn vars;
  strSSID.toCharArray(vars.eSsid, sizeof(vars.eSsid));
  strPW.toCharArray(vars.ePasw, sizeof(vars.ePasw));
  EEPROM.put(startAddr, vars);
  EEPROM.commit();  
}
wifiConn read_wifi_fromEEPROM(uint8_t startAddr){
  wifiConn readEE;        //Variable to store custom object read from EEPROM.
  EEPROM.get(startAddr, readEE);
  Serial.println("Read ssid object from EEPROM ");
  return readEE;    
}
相关问题