首页 > 解决方案 > Powershell - Read CSV contents, copy file from a network drive to local machine

问题描述

I am currently in the process of restructuring a Windows server file directory and need to bulk rename over 10,000 files all in different folders but most have duplicate filenames (e.g 0001.pdf, 0002.pdf)

I have written a Powershell script to help me do this but I am having some trouble with the execution. The script reads a csv file (export of all the files in the folder structure - export.csv) then creates the variables $OldFilename & $NewFileName. The variables are then used to locate the old file location and copy it to a new destination using the Copy-Item command for each row in the CSV.

Code

$csv = import-csv c:\tmp\test.csv
$csv | foreach-object {
  $OldFileName =$_.OldFileName
  $NewFileName = $_.NewFileName
}
$csv | ForEach-Object {
      $OldFileName =$_.OldFileName
      $NewFileName = $_.NewFileName

Copy-Item $OldFileName -Destination $NewFileName   

}

CSV is formatted as such

OldFileName,NewFileName
"X:\Folder1\0001.pdf","C:\temp\File0001.pdf"
"X:\Folder2\0001.pdf","C:\temp\File0002.pdf"
"X:\Folder3\0001.pdf","C:\temp\File0003.pdf"

Code does not error when run but files do not appear.

A Write-Output displays the correct file path but a Write-Host((Get-Item $file).length/1MB) does not retrieve the files size which leads me to believe there is an issue with the variable!?

Something I need to add?

Many Thanks

Jonny

标签: powershellcsvwindows-10

解决方案


推荐阅读