powershell 每天我都会收到不同路径中的多个文件,并希望将每个文件复制到每个路径中的特定文件夹

6yoyoihd  于 2022-11-10  发布在  Shell
关注(0)|答案(2)|浏览(125)

每天有3个新的CSV文件被发送到3个不同的路径。我想将这些文件复制到每个路径中的存档中,然后运行一个脚本来删除每个文件的第一行。然后,生成的文件被移到另一个文件夹,在那里批处理可以读取它们。
路径1的示例:“Z:\TEST\1\SCRIPT\EXPORT_2022-11-09.csv”归档的示例1:“Z:\Test\1\Script\Archive\Export_2022-11-09.csv”
路径2的示例:“Z:\TEST\2\SCRIPT\EXPORT_2022-11-09.csv”归档的示例2:“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 $_
}

每个文件的第一行被删除的部分工作得很好,但我想不出一种方法来将每个文件复制到特定和不同的路径。如果能帮上忙,我将不胜感激。提前谢谢您。

mxg2im7a

mxg2im7a1#

尝试以下操作以获取新文件名

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
}
b09cbbtk

b09cbbtk2#

似乎您想要的是将原始文件保存在同一路径下的归档子文件夹中。然后重写原始文件,以便删除标题行。
使用[System.IO.Path]::GetDirectoryName()将路径从完整路径和文件名字符串中分离出来,然后用‘存档’将其连接起来

$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..
}

相关问题