Renaming doesn't work properly sometimes

youki 1,021 Reputation points
2023-02-24T22:50:47.7466667+00:00

Hi,

I'm trying to find an error. The error occurs when renaming.

The code below renames a file to Test.pdf and after editing renames it back to the original name but appending an extension (.edited).

Sometimes it happens that the file does not have the original name but is called Test.pdf.edited.

The code is not mine and works fine for thousands of files, but unfortunately not for a few files a day.

What could be the reason, has anyone seen such behavior before. Can it be due to a permission or that another process is still accessing it or a property that distinguishes the file from others?

$path = 'xxx\xxx'
$filter = '*.pdf'
...
$files = Get-ChildItem -Path $path  -Name $filter

foreach($file in $files)
{
  # File gets renamed to Test.pdf  
  Rename-Item $path\$file 'Test.pdf' -Force

  #...Content from file will be extracted here by Get-Content for the email.
  ...

  #...File will be send by email here...
  ...

  # File gets renamed to the original name + .edited (MyFileName.pdf.edited)
  Rename-Item  $path'\Test.pdf' "$path\$file.edited" -Force
}
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2023-02-25T03:30:57.8666667+00:00

    I'm surprised that worked at all!

    $path = "xxx\xxx"
    $files = Get-ChildItem -Path $path -File -Filter *.pdf 
    
    foreach($file in $files)
    {
      # File gets renamed to Test.pdf  
      Rename-Item -Path $file.FullName 'Test.pdf' -Force
    
      #...Content from file will be extracted here by Get-Content for the email.
      #...
    
      #...File will be send by email here...
      #...
    
      # File gets renamed to the original name + .edited (MyFileName.pdf.edited)
    
      # If the $file variable has its FullName value equal to C:\junk\test.csv, then
      # the result of "$path\$file.edited" looks like "xxx\xxx\C:junk\test.csv.edited"!
      # Rename-Item  $path'\Test.pdf' "$path\$file.edited" -Force
      #
      #
      Rename-Item ($file.DirectoryName + '\Test.pdf') "$($File.Name).edited" -Force
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.