xlogI125’s blog

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

GetDetailsOfメソッドでファイルの詳細を取得 2

メモ

  • GetDetailsOfで取得した文字列に含まれる '[\p{Cc}\p{Cf}]' を '' に置換
  • ディレクトリパスをInteraction.InputBoxのテキストボックス部分に入力

使い捨てスクリプト

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

using namespace Microsoft.VisualBasic

Set-StrictMode -Version Latest

Add-Type -AssemblyName @(
  "Microsoft.PowerShell.Commands.Utility", 
  "Microsoft.VisualBasic"
)

try {
  $str = [Interaction]::InputBox("ディレクトリパス", "入力", "${env:USERPROFILE}\Desktop", -1, -1)

  Set-Location -LiteralPath $str -ErrorAction Stop

  $fileDetails = & {
    # Get-ChildItem
    $fInfos = [System.IO.FileInfo[]]@(Get-ChildItem -Recurse -Depth 1 -File)

    # ディレクトリ名で分類
    $grs = [Microsoft.PowerShell.Commands.GroupInfo[]]@(
      $fInfos | Group-Object -Property DirectoryName
    )

    # List
    $psObjList = [System.Collections.Generic.List[PSObject]]::new()

    # HashSet
    $propNameSet = [System.Collections.Generic.HashSet[string]]::new()

    # Shell.Application
    $shApp = New-Object -ComObject "Shell.Application"

    foreach ($gr in $grs) {
      $dirName = $gr.Name  # ディレクトリ名
      $folder = $shApp.NameSpace($dirName)
      $files = [System.IO.FileInfo[]]@($gr.Group)

      # フォルダ内のファイル
      foreach ($file in $files) {
        $folderItem = $folder.ParseName($file.Name)

        # OrderedDictionary
        $fileDetail = [ordered]@{}

        # GetDetailsOf
        for ($col = 0; $col -lt 384; $col++) {
          $title = $folder.GetDetailsOf($null, $col) -replace '[\p{Cc}\p{Cf}]', ''
          $propName = $col.ToString("000") + ":" + $title
          $val = $folder.GetDetailsOf($folderItem, $col) -replace '[\p{Cc}\p{Cf}]', ''

          if ($val -ne "") {
            $fileDetail.Add($propName, $val)
            [void]$propNameSet.Add($propName)
          }
        }

        $psObjList.Add([PSCustomObject]$fileDetail)

        $folderItem = $null
      }

      $folder = $null
    }

    $shApp = $null

    # 単項配列式
    return (, @($psObjList | Select-Object -Property @($propNameSet | Sort-Object)))
  }

  if ($fileDetails.Length -ne 0) {
    try {
      $prop = 
        @($fileDetails[0].PSObject.Properties.Match("*ファイルの場所*").Name) + 
        @($fileDetails[0].PSObject.Properties.Match("*ファイル拡張子*").Name)
    }
    catch {
      $prop = $null
    }

    $outObjs = $fileDetails | Sort-Object -Property $prop

    $outObjs | ConvertTo-Csv -NoTypeInformation | Set-Clipboard
    $outObjs | Out-GridView
  }
}
catch {
  throw
}