xlogI125’s blog

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

PowerShell練習 [System.Action]{} # lambda_method

ScriptBlockDelegateに変換しようとするとlambda_methodになる様子

# PowerShell 5.1, Windows 11 (2023年12月頃)
$lambdaMethod = [System.IO.FileSystemEventHandler]([ScriptBlock]::Create(""))
$lambdaMethod | Format-List

引数の確認

# PowerShell 5.1, Windows 11 (2023年12月頃)
$lambdaMethod = [System.IO.FileSystemEventHandler]{}
$lambdaMethod | Get-Member -Name Invoke

$argsの確認

# PowerShell 5.1, Windows 11 (2023年12月頃)
$lambdaMethod = [System.IO.FileSystemEventHandler]{
  Get-Variable -Scope Local -Name args | Out-String | Write-Host
}
$lambdaMethod.Invoke($null, $null)

引数の確認

# PowerShell 5.1, Windows 11 (2023年12月頃)
([System.Func[string, string, string]]{}).Invoke

paramを使う場合の確認

# PowerShell 5.1, Windows 11 (2023年12月頃)
([System.Func[string, string, string]]{
  param ([string]$arg1, [string]$arg2)
  $arg1 + $arg2 | Write-Host
  Get-Variable -Scope Local | Out-String -Width 80 | Write-Verbose -Verbose
}).Invoke("abc", "def")

List<T>.Sort(Comparison<T>)の確認

# PowerShell 5.1, Windows 11 (2023年12月頃)

Add-Type -Language CSharp -TypeDefinition @'
using System.Runtime.InteropServices;
namespace Win32API {
  public class Shlwapi {
    [DllImport("Shlwapi.dll", EntryPoint = "StrCmpLogicalW", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(
      [MarshalAs(UnmanagedType.LPWStr)] string psz1, 
      [MarshalAs(UnmanagedType.LPWStr)] string psz2
    );
  }
}
'@

$psObjList = [System.Collections.Generic.List[PSObject]][PSObject[]]@(Get-ChildItem)

$psObjList | Select-Object -Property Name | ForEach-Object { Write-Host $_.Name -ForegroundColor Green }
<#
文書1.txt
文書10.txt
文書100.txt
文書5.txt
文書50.txt
#>

$cmp = [System.Comparison[PSObject]]{
  param ([PSObject]$x, [PSObject]$y)
  return [Win32API.Shlwapi]::StrCmpLogicalW($x.Name, $y.Name)
}

$psObjList.Sort($cmp)

$psObjList | Select-Object -Property Name | ForEach-Object { Write-Host $_.Name -ForegroundColor Cyan }
<#
文書1.txt
文書5.txt
文書10.txt
文書50.txt
文書100.txt
#>