Skip to content

Instantly share code, notes, and snippets.

@hsytkm
Created February 24, 2024 01:40
Show Gist options
  • Save hsytkm/331aa558c38ed32d607e1eab9b08f18e to your computer and use it in GitHub Desktop.
Save hsytkm/331aa558c38ed32d607e1eab9b08f18e to your computer and use it in GitHub Desktop.
Command to display file names with windows sorting rules
@echo off
setlocal
set BAT_PATH=%~f0
powershell -NoProfile -Command "& {$cscode=[regex]::Split([IO.File]::ReadAllText($env:BAT_PATH,[Text.Encoding]::UTF8),':EndBatch')[2]; Add-Type -TypeDefinition $cscode -Language CSharp; [CSBatch.Program]::Main($Args);}" %*
endlocal
exit /b
:EndBatch
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace CSBatch
{
public class Program
{
public static void Main(string[] args)
{
string targetDir = args.Length == 0 ? ".": args[0];
if (!Directory.Exists(targetDir))
{
Console.WriteLine("Usage : lswin.bat [directory path]");
return;
}
foreach (var path in FilePathUtil.GetWindowsOrderedFilePaths(targetDir))
{
var name = path.StartsWith(@".\") ? path.Substring(2) : path;
Console.WriteLine(name);
}
}
}
static class FilePathUtil
{
public static IOrderedEnumerable<string> GetWindowsOrderedFilePaths(string directoryPath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return Directory.EnumerateFiles(directoryPath, searchPattern, searchOption).OrderBy(x => x, FileNameComparer.Default);
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
private sealed class FileNameComparer : IComparer<string>
{
public static readonly FileNameComparer Default = new FileNameComparer();
public int Compare(string x, string y)
{
if (x == null && y == null)
return 0;
if (x != null && y == null)
return 1;
if (x == null && y != null)
return -1;
return StrCmpLogicalW(x, y);
}
}
}
}
/* Windowsのファイル名のソートルールで
* 指定ディレクトリのファイル名を表示します。
*
* □動作例
*
* // PowerShell
* > ls -Name .
* 1.txt
* 10.txt
* 9.txt
*
* // cmd
* > dir /B .
* 1.txt
* 10.txt
* 9.txt
*
* > lswin.bat .
* 1.txt
* 9.txt
* 10.txt
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment