xlogI125’s blog

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

PowerShell練習 .Sort([Delegate]::CreateDelegate([Comparison[T]], Type, "StrCmpLogicalW"))

メモ

クリップボード内のテキストをStrCmpLogicalWの順で並べ替えたものをクリップボードにコピーする

使い捨てスクリプト

# PowerShell 5.1, Windows 11

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

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

Set-StrictMode -Version Latest

$str = [System.Collections.Generic.List[string]](
  @(Get-Clipboard -Format Text -TextFormatType UnicodeText) -ne ""
)

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

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

$str.Sort(
  [System.Delegate]::CreateDelegate(
    [System.Comparison[string]], [MyNamespace.MyClass], "StrCmpLogicalW"
  )
)

Write-Host ($str -join "`n")

$str -ne "" | Set-Clipboard