xlogI125’s blog

パソコン作業を効率化したい

PowerShell練習 List.Sort(Comparer<PSObject>)

メモ

  • List.Sort(Comparer<PSObject>) で並べ替え

使い捨てスクリプト

# PowerShell 5.1, Windows 11

# このスクリプトのファイル名
#  "%USERPROFILE%\Desktop\test.ps1"
# エンコード
#  UTF-8 (BOM付き)

# ショートカット(.lnk)
#  リンク先(T):
#   PowerShell.exe -NoLogo -NoExit -ExecutionPolicy RemoteSigned -File "%USERPROFILE%\Desktop\test.ps1"
#  作業フォルダー(S):
#   ""

using namespace System.Collections.Generic

Set-StrictMode -Version Latest

$fileList = Get-Clipboard -Format FileDropList
if ($null -eq $fileList) {
  return
}

Write-Host $fileList.GetType().FullName
Write-Host $fileList[0].GetType().FullName
Write-Host ""

Add-Type -Language CSharp -TypeDefinition @'
namespace Win32Functions {
  using System.Runtime.InteropServices;

  public class Win32StrCmpLogicalW {
    [DllImport(
      "Shlwapi.dll", CharSet = CharSet.Unicode, EntryPoint = "StrCmpLogicalW"
    )]
    public static extern int StrCmpLogicalW(
      [MarshalAs(UnmanagedType.LPWStr)] string psz1, 
      [MarshalAs(UnmanagedType.LPWStr)] string psz2
    );
  }
}

namespace MyNamespace {
  using System.Collections.Generic;
  using System.Management.Automation;

  public class MyClass : Comparer<PSObject> {
    private string propertyName;

    public MyClass(string propertyName) {
      this.propertyName = propertyName;
    }

    public override int Compare(PSObject x, PSObject y) {
      string str1 = x.Properties[propertyName].Value.ToString();
      string str2 = y.Properties[propertyName].Value.ToString();
      return Win32Functions.Win32StrCmpLogicalW.StrCmpLogicalW(str1, str2);
    }
  }
}
'@

$fileList.Sort([MyNamespace.MyClass]::new("Name"))

Write-Host ($fileList.Name -join "`n")