Home > Mobile >  How can I modify this PowerShell script to include changing directory names to lower?
How can I modify this PowerShell script to include changing directory names to lower?

Time:01-04

I am trying to rename all files and directories to lower and I found a powershell script here: Rename files to lowercase in Powershell

My favorite answer is the following because it is the cleanest and most concise answer. However, it does not include directory names and I don't have enough rep yet to respond to the comment

Get-ChildItem -r | Where-Object { !$_.PSIsContainer } | Rename-Item -NewName { $_.FullName.ToLower() }

I don't know PowerShell and I don't intend to become proficient, please skip all the details I'm just looking for code to rename all my files and directories to lower and I don't need to know anything about how it works. I don't like the following solution because 1, it is too wordy and 2, it only does directory names and not file names.

Where-Object { $_.PSIsContainer -And $_.Name -CMatch "[A-Z]" } |
ForEach-Object {
    $NName = $_.Name.ToLowerInvariant()

    # Set temporary name to enable rename to the same name; Windows is not case sensitive
    $TempItem = Rename-Item -Path $_.FullName -NewName "x$NName" -PassThru

    Rename-Item -Path $TempItem.FullName -NewName $NName
}

I want one clean command to rename files and directories, similar to the first example, please


when i first wrote this, i just wanted to open powershell and paste a command. in hindsight, that is not most efficient way either. so i ended up saving each script (one for files, one for folders) into one .ps1 file that you put in whatever directory you want to lower, then right-click and "run with powershell" and it will rename all files and subdirectories

the script looks like this:

# files to lower
Get-ChildItem -r | Where-Object { !$_.PSIsContainer } |
Rename-Item -NewName { $_.FullName.ToLower() }

# folders to lower
$fso = New-Object -ComObject Scripting.FileSystemObject
Get-ChildItem . -rec -dir |
ForEach-Object { $fso.MoveFolder($_.fullname, $_.Fullname.ToLower()) }

CodePudding user response:

as you mentioned on your provided code, Windows is not a case sensitive OS, so you need to rename the directories to a temp name (for example insert a character after lowering it) then rename it again (by removing the inserted character)

i modified your line as follow to be able to lower both directories and files, please give it a try

Get-ChildItem -r  | Rename-Item -NewName { $_.Name.ToLower().Insert(0,'_') } -PassThru |  Rename-Item -NewName { $_.Name.Substring(1) }
  •  Tags:  
  • Related