PowerShell – Loop through files and rename

Question:

newbie here. I am trying to write a PowerShell script to:

  1. loop through all files in directory
  2. List item
  3. Get all .pdf files ONLY

    Rename them-the file names are long – over 30 chars
    -They contain 2 numbers which I need to extract
    -Example:

    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf ->
    RESULT : = 18CU11.pdf

I tried examples from bunch of sites and I can’t seem to even loop successfully.
Either get an error – that path doesn’t exist or that can’t rename files as somehow loop gets a filepath and that I can’t rename

That’s just latest attempt, but any other ways of doing it will be fine – as long as it does the job.

Answer:

Try this logic:

Source:

PowerShell - Loop through files and rename by licensed under CC BY-SA | With most appropriate answer!

, '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}

Source:

PowerShell – Loop through files and rename by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply