1

From root folder, I am trying to search all files in subdirectories with "-poster" and rename those files to only poster without changing the file extension. All these files have other text in front of the "-poster" that I want to remove, and all the files are .jpgs.

Would a command such as this work:

Get-ChildItem -filter *-poster* -recurse | ForEach {Rename-Item $_ -NewName "poster.jpg"}

I haven't tried it, as don't want to risk changing other files.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • To avoid or minimize the risk you could simply create some test data in a test folder structure and test your code there?! `¯\_(ツ)_/¯` – Olaf Feb 09 '23 at 22:45
  • Create a test folder and put some copies of your files there, and use that folder for testing. *I haven't tried it* is lame - there's no risk in testing if you set up a test folder, and you learn a lot by trying things yourself instead of depending on asking others first. – Ken White Feb 10 '23 at 00:30

1 Answers1

1

Use the -WhatIf common parameter to preview an operation without actually performing it:

Get-ChildItem -Filter *-poster* -Recurse |
  Rename-Item -NewName poster.jpg -WhatIf

Note:

  • -WhatIf does not test actual runtime conditions.

  • That is, if a poster.jpg file already exists in the target directory, the Rename-Item call will fail once -WhatIf is removed.

  • To handle this case, you have the following options, depending on your use case:

    • Allow the failure, if you don't expect a preexisting file.

    • Ignore the failure, if a preexisting file implies that no action is needed: add -ErrorAction Ignore to the Rename-Item call.

    • Blindly overwrite the existing file, by adding -Force to the Rename-Item call.

    • Create a file with a different name, such as by appending a sequence number, using a delay-bind script block - see below.

Get-ChildItem -Filter *-poster* -Recurse |
  Rename-Item -NewName {
    $newBaseName = 'poster.jpg'
    $newBaseName = [IO.Path]::GetFileNameWithoutExtension($newName)
    $newExtension = [IO.Path]::GetExtension($newName)
    $suffix = '' 
    if ([array] $preexisting = Get-ChildItem -File -LiteralPath $_.DirectoryName -Filter "$newBaseName*$newExtension")) {
      $highestNumSoFar = [int[]] ($preexisting.BaseName -replace '^.*\D') | Sort-Object -Descending | Select-Object -First 1
      $suffix = $highestNumSoFar + 1
    }
    $newBaseName + $suffix + $newExtension
  } -WhatIf
mklement0
  • 382,024
  • 64
  • 607
  • 775