2

I have a bunch of html files that I need to rename with url encoding before I upload them to the server. I've tried:

Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html | Rename-Item -NewName { $_.Name.replace("*.html",[Web.Httputility]::UrlEncode("*.html")) }

But that doesn't apply the encoding, can this be even done somehow?

2 Answers 2

1

Here's a basic way to do it, based on this answer:

(Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -File) |
foreach { ren $_.fullname ([uri]::EscapeDataString($_))}

Originally I had written it without the () around the Get-ChildItem, but found it was still reading directory information while the rename had already renamed the first item. Then the rename reencoded the first item a second time, thus making it a bit munged up.

Here's a cleaner version that handles the files first and then folders:

$files = Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -File
$folders = Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -Directory
$files | foreach { ren $_.fullname ([uri]::EscapeDataString($_))}
$folders | foreach { ren $_.fullname ([uri]::EscapeDataString($_))}
Sign up to request clarification or add additional context in comments.

4 Comments

This also adds path to the filenames, how can i avoid that?
@ BoogaRoo Your solution doesn't work , because top folder gets renamed and therefor path to the files inside it will change and so they can't be found any more.
Sorry i forgot to mention folders in my original question
@PeterPavelka Alright, I think the updated cleaner version suits your situation and also avoids accidentally renaming folders first. If this is not the case, it may help to update the question with folder structure and additional requirements.
0

Based on your answers i did this to make it work

(Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html) |
foreach { ren $_.fullName ([uri]::EscapeDataString($_.Name))} | Out-Null

Get-ChildItem -Path c:\temp\ -Recurse | ?{ $_.PSIsContainer } |
 foreach { ren $_.fullName ([uri]::EscapeDataString($_.Name))}

First I had to do only files and then folders, because when top folder gets renamed, then the path to files inside it doesn't exist any more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.