Thursday, January 9, 2020

To list (dir command) file names sorted by their name's length


Suppose we want to list certain files (or all files in a directory), but sorted ascending by their filename's length.

The following small script meets the purpose:

First, create a PowerShell script, say, dirnamesize.ps1 with its content as below:

param (
   [string]$dirpath = "."
)

gci $dirpath | select-object name, @{Name="Nlength";Expression={$_.Name.Length}} | sort-object Nlength


Second, create a normal DOS shell file to call that PowerShell (so we don't need to open PowerShell), say, dirnamesize.cmd with the content:

set DIRPATH=%*

@if "%DIRPATH%"=="" (
    powershell dirnamesize.ps1
) else (
    powershell dirnamesize.ps1 -dirpath %DIRPATH%
)


Example:

C:\Windows>dirname *.xml

Name                        Nlength
----                        -------
Education.xml                    13
ServerRdsh.xml                   14
Enterprise.xml                   14
Professional.xml                 16
ProfessionalEducation.xml        25
ProfessionalWorkstation.xml      27


No comments:

Post a Comment