Home > database >  Every day I get multiple files in different paths and want to copy each file to a specific folder wi
Every day I get multiple files in different paths and want to copy each file to a specific folder wi

Time:11-10

Every day 3 new CSV-files are sent to 3 different paths. I want to copy these files to an archive within each path and then run a script which removes the first line of each file. The resulting files are then moved to another folder where a batch reads them.

Example for a path1: "Z:\Test\1\Script\Export_2022-11-09.csv" Example for an archive1: "Z:\Test\1\Script\Archive\Export_2022-11-09.csv"

Example for a path2: "Z:\Test\2\Script\Export_2022-11-09.csv" Example for an archive2: "Z:\Test\2\Script\Archive\Export_2022-11-09.csv"

$Files = @( "Z:\Test\1\Script\Export_2022-11-09.csv", "Z:\Test\2\Script\Export_2022-11-09.csv")

$Files | ForEach-Object {
    Copy-Item $_ -Destination 
    (Get-Content $_ | Select-Object -Skip 1) | Set-Content $_
}

The part where the first line of each file gets deleted works fine, but i can't think of a way to have each file copied to a specific and different path before. I would very much appreciate some help. Thank you in advance.

CodePudding user response:

Try following to get new filename

Files = @( "Z:\Test\1\Script\Export_2022-11-09.csv", "Z:\Test\2\Script\Export_2022-11-09.csv")
foreach($File in $Files)
{
   $lastIndex = $File.LastIndexOf("\")
   $baseFilename = $File.Substring($lastIndex   1)
   $newFilename = $File.Substring(0, $lastIndex   1)
   $newFilename  = "Archive\"   $baseFileName
   Write-Host "New File Name = " $newFilename
}

CodePudding user response:

It seems what you want is to save the original files in an Archive subfolder within the same path. Then rewrite the original file so the header line gets removed.

Use [System.IO.Path]::GetDirectoryName() to split the path from the full path and filename string, then join it with 'Archive'

$Files = "Z:\Test\1\Script\Export_2022-11-09.csv", "Z:\Test\2\Script\Export_2022-11-09.csv"

$Files | ForEach-Object {
    # construct the archive path
    $archivePath = Join-Path -Path ([System.IO.Path]::GetDirectoryName($_)) -ChildPath 'Archive'
    # create that folder if it does not already exist
    $null = New-Item -Path $archivePath -ItemType Directory -Force
    # copy the file as-is
    Copy-Item -Path $_ -Destination $archivePath

    # now remove the header line from the original file
    (Get-Content $_ | Select-Object -Skip 1) | Set-Content $_

    # for the final part, Move to another folder where a batch reads them, I will need more info
    # does every file have the SAME final destination folder? In that case, since all files are
    # named the same you will get file naming collisions there..
}
  • Related