xlogI125’s blog

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

PowerShell練習 Add-Type (StrCmpLogicalW) 2

使い捨てスクリプト

現在のフォルダ内にあるファイル名をソートして取得

  • このスクリプトを起動させるショートカット(.lnk)をSendToフォルダに入れて使用
# PowerShell 5.1, Windows 11

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

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

# SendToフォルダ
#  %APPDATA%\Microsoft\Windows\SendTo

Set-StrictMode -Version Latest

# デスクトップに移動
# Set-Location "${env:USERPROFILE}\Desktop"

# ファイル名を取得
$gci = @(Get-ChildItem -Force -File -Name)

$srcCSharp = @'
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

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

    public static List<string> SortStrCmpLogicalW(string[] str) {
      List<string> tmp = new List<string>(str);
      tmp.Sort(StrCmpLogicalW);
      return tmp;
    }
  }
}
'@

Add-Type -Language CSharp -TypeDefinition $srcCSharp

# ソート
$str = [MyNamespace.MyClass]::SortStrCmpLogicalW($gci)

# 画面に表示
Write-Host ($str -join "`n")

# クリップボードにコピー
$str | Set-Clipboard

クリップボード内のテキストをソート

# 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 = @(Get-Clipboard -Format Text -TextFormatType UnicodeText)

$srcCSharp = @'
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

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

    public static void SortStrCmpLogicalW(ref string[] str) {
      List<string> tmp = new List<string>(str);
      tmp.Sort(StrCmpLogicalW);
      tmp.CopyTo(str);
    }
  }
}
'@

Add-Type -Language CSharp -TypeDefinition $srcCSharp

# ソート
[MyNamespace.MyClass]::SortStrCmpLogicalW([ref]$str)

# 画面に表示
Write-Host ($str -join "`n")

# クリップボードにコピー
$str | Set-Clipboard

過去記事

dy100ms.hatenadiary.jp