renaming files with powershell or for loop …
i have a directory of scripts with names like mom_myScript.vbs or sms_myScript.vbs. this is all so that i can do a relatively simple directory search to see what kind of scripts i have for a particular technology i’m working with. the problem is, i flip-flip on my use of hyphens and underscores and have apparently done it often enough to warrant a little a clean up.
first, the old way i would have done this in cmd shell. it’s basically a for loop to go through the list of files in a directory that matches where the script has a hyphen. to pull back just the file name, i’m using the dir /b command. i’ve broken down the file name into tokens that’s separated by the hyphen and then renaming the files, positioning underscore between the tokens.
for /f "tokens=1-2 delims=-" %a in ('dir /b mom-*.*') do @ren %a-%b %a_%b
here’s my new, preferred way to do it in powershell. basically, i’m pulling back the list of files i want to work with and passing it through to the rename-item cmdlet. the script block here is pretty cool. i can run a replace on the fly which doesn’t require any token breakdowns, etc.
dir mom-*.* | ren -NewName {$_.Name –replace 'mom-','mom_'}
You can rename all files in a folder to uppercase:
ReplyDelete$f = "$HOME\myFiles"
dir $f | Rename-Item -NewName {$_.Name.ToUpper()}