Question:
newbie here. I am trying to write a PowerShell script to:
- loop through all files in directory
- List item
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Get-ChildItem "C:\Users\******\Desktop\PowerShell Practice" -Filter *.pdf | #create list of files ForEach-Object{ $oldname = $_.FullName; $newname = $_.FullName.Remove(0,17); #$newname = $_.FullName.Insert(0,"CU") Rename-Item $oldname $newname; $oldname; $newname; #for testing } |
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:
1 2 3 4 5 6 7 8 |
[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop\PowerShell Practice' [string[]]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName $listOfFilesToRename | ForEach-Object { #get the filename wihtout the directory [string]$newName = Split-Path -Path $_ -Leaf #use regex replace to apply the new format $newName = $newName -replace '^Cumulative Update (\d+) .*NAV 20(\d+).* |
Source:
PowerShell - Loop through files and rename by stackoverflow.com 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
}