自动修改 powershell 中的 .csv 文件

Modify a .csv file in powershell automatically

我尝试创建一个 powershell 脚本,执行几个步骤:

$ErrorActionPreference = 'Stop'

Function Convert-CsvInBatch
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)][String]$Folder
    )
    $ExcelFiles = Get-ChildItem -Path $Folder -Filter *.xlsx -Recurse

    $excelApp = New-Object -ComObject Excel.Application
    $excelApp.DisplayAlerts = $false

    $ExcelFiles | ForEach-Object {
        $workbook = $excelApp.Workbooks.Open($_.FullName)
        $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv"
        $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV)
        $workbook.Close()
    }

    # Release Excel Com Object resource
    $excelApp.Workbooks.Close()
    $excelApp.Visible = $true
    Start-Sleep 5
    $excelApp.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelApp) | Out-Null
}

#
# 0. Prepare the folder path which contains all excel files
$FolderPath = "C:\exacthpath"

Convert-CsvInBatch -Folder $FolderPath

此时我卡住了。我可以像这样将它导入 Powershell:

Import-Csv -Path 'C:\folder\filename.csv' | ForEach-Object {
$_
}

我明白了,最重要的任务在这里,只在第一行:

H;1;43;185;

这里要修改成:

H;01;43;185

其余的应该保持不变。 在我需要将其导出回 CSV 文件后,例如:

Export-Csv -Path 'C:\folder\modified_filename.csv'

但是整个过程应该插入到一个单独的 powershell 脚本中,该脚本会自行执行上述步骤。简而言之:

你能帮我把上面的脚本include/optimize也让powershell执行修改吗?像这样的文件的示例内容(最终外观)通常它包含 1000 多行:

H;01;43;185
D;111;3;1042;2
D;222;3;1055;3
D;333;3;1085;1
T;3;;;

非常感谢任何帮助。

此致, 阿敏

如果正如您在评论中所说,您的 Excel 已经创建了一个以分号作为分隔符的 csv,您可以在循环内执行此操作,就在 $workbook.Close()[=14= 下面]

# read the file created by Excel as string array
$data = Get-Content $csvFilePath
# overwrite the file with just the new header
Set-Content -Path $csvFilePath -Value 'H;01;43;185'
# add the rest of the data to the file
$data[1..($data.Count -1)] | Add-Content -Path $csvFilePath

P.S。我会删除行

$excelApp.Visible = $true
Start-Sleep 5

因为我认为不需要让 Excel 显示自己并暂停该功能 5 秒。相反,让 Excel 根本不显示,这样它会工作得更快添加

$excelApp.Visible = $false

在您创建 $excelApp

之后