Home > Enterprise >  How to rename files(and move them) in PowerShell 5.1?
How to rename files(and move them) in PowerShell 5.1?

Time:02-24

I am new to PowerShell and I am stuck at something really simple. I have Googled a lot and got this far but can't seem to resolve this. I am trying to do a simple file transfer from one server to the other. The purpose of the script is to check if the file in the source folder exists in the destination folder, if it does, prepend "Copy_" in the name of the file and move all the contents of the folder including the renamed files in the destination folder.

Move-Item works but it moves all the content before renaming them. Therefore, there are no issues with the paths or the connection.

Write-Output $file returns True which is correct, there are duplicate files in the destination folder. The issues are:

  1. Renaming of files is not working. It just adds a new file called "Copy_" in the source folder. All the files except this new "Copy_" file are moved.
  2. I get this error for each file in the source folder Get-ChildItem : Could not find item \\server9\VantageAttachments_ProblemsFolder\Vantage_test\NameOfTheFile.txt. Which is triggered by line Get-ChildItem -Force $sourcePath | ForEach-Object
$sourcePath = "\\server9\VantageAttachments_ProblemsFolder\Vantage_test\*.*"
$DestinationPath = "\\server2\MfgLib\RevisedPrograms\MC-A\Copied_From_Mazak"

Get-ChildItem -Force $sourcePath | ForEach-Object {
    # Check if the file in the Source folder is in Destination folder
    $fileName = $_.Name
    $file = Test-Path -Path $DestinationPath\$fileName
    Write-Output $file
    if($file){
        "\\server9\VantageAttachments_ProblemsFolder\Vantage_test\$fileName" | Rename-Item -NewName {"Copy_" $_.Name};
        
    }
    Move-Item -Path $sourcePath  -Destination $DestinationPath -Force

}

Thanks in advance.

CodePudding user response:

Copy_ is not being moved because in $source you specified that a file has to have an extension *.*. Try using parentheses instead of curly brackets in Rename-Item. I think that it is a scoping error, and that because of that $_.Name is empty.

CodePudding user response:

$sourcePath = "\\server9\VantageAttachments_ProblemsFolder\Vantage_test\*.*"
$DestinationPath = "\\server2\MfgLib\RevisedPrograms\MC-A\Copied_From_Mazak"

Get-ChildItem -Force $sourcePath | ForEach-Object {
    # Check if the file in the Source folder is in Destination folder
        $fileName = $_.Name
        $file = Test-Path -Path $DestinationPath\$fileName
        Write-Output $file
            if($file){
                 "\\server9\VantageAttachments_ProblemsFolder\Vantage_test$fileName" | Rename-Item -NewName ("Copy_" $_.Name);
            }
           
}
Move-Item -Path $sourcePath  -Destination $DestinationPath -Force
  • Related