Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply powershell to subfolders

I have a lot of folders with image files that accidentally saved without extension.
I’ve managed to work out how to add the extension:

ls -file | ? {$_.extension -eq ''} | % {ren $_ ($_.name + '.jpeg')}

… but I can’t work out how to make it apply to all subfolders.
This command doesn’t work:

Get-ChildItem -Recurse ls -file | ? {$_.extension -eq ''} | % {ren $_ ($_.name + '.jpeg')}

any ideas where I’m going wrong, please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First, make sure to remove ls from Get-ChildItem -Recurse ls -filels is an alias for Get-ChildItem, and since you’ve already specified the cmdlet name PowerShell will attempt to locate a folder named ls and start the search from there.

Second, instead of passing $_ to Rename-Item (alias ren) as a positional argument, pipe it:

Get-ChildItem -Recurse -File | ? {$_.extension -eq ''} | Rename-Item -NewName { $_.Name + '.jpeg' }

Piping the whole file info object to Rename-Item allows PowerShell to bind the correct absolute path to the file system object, and it’ll thus start working for files in nested folders.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading