PowerShell ファイル検索結果をExcel出力させるサンプル

PowerShellカテゴリを表すパンダのイラスト PowerShell

PowerShellで、ファイル検索した結果をExcel出力させるサンプル

まずは、出力先のファイルパスと検索対象のファイルパスを指定する。

$FileName = "Out.xlsx"
$FullPath = Join-Path $PSScriptRoot $FileName
$CheckPath = $PSScriptRoot 

Excel出力用の見出し列をenumで定義(VBAでよく使うパターン)

#excel用の見出し列
enum LayOut {
    DirectoryName = 1
    Name 
    CreationTime 
    LastAccessTime 
    LastWriteTime 
}

Get-ChildItem でファイル情報を取得、Excelを作成

#------ 処理開始
$datas = Get-ChildItem -Force -Path  $CheckPath 
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$book = $excel.Workbooks.Add()
$book.Sheets(1).Name = "ファイル一覧"
$sheet = $book.Sheets("ファイル一覧")

結果出力

#ヘッダ
$RowIndex = 1
$sheet.Cells.Item($RowIndex, [LayOut]::DirectoryName) = "DirectoryName"
$sheet.Cells.Item($RowIndex, [LayOut]::Name) = "Name"
$sheet.Cells.Item($RowIndex, [LayOut]::CreationTime) = "CreationTime"
$sheet.Cells.Item($RowIndex, [LayOut]::LastAccessTime) = "LastAccessTime"
$sheet.Cells.Item($RowIndex, [LayOut]::LastWriteTime) = "LastWriteTime"

#データ書き込み
foreach ($data in $datas) {

    $sheet.Cells.Item($RowIndex, [LayOut]::DirectoryName) = $data.DirectoryName
    $sheet.Cells.Item($RowIndex, [LayOut]::Name) = $data.Name
    $sheet.Cells.Item($RowIndex, [LayOut]::CreationTime) = $data.CreationTime
    $sheet.Cells.Item($RowIndex, [LayOut]::LastAccessTime) = $data.LastAccessTime
    $sheet.Cells.Item($RowIndex, [LayOut]::LastWriteTime) = $data.LastWriteTime    
    $RowIndex++
}

保存

#保存
$book.SaveAs($FullPath)
$excel.Quit()
$excel = $null

文書情報

記事タイトル
PowerShell ファイル検索結果をExcel出力させるサンプル
作成日
更新日
Source URL
https://papanda925.com/?p=1893

ライセンス: 本記事のうち、当サイトが権利を有する本文・自作図表は、特記なき限り CC BY 4.0 で利用できます。生成AIを活用して作成・編集した内容を含みます。コードについて、別途ライセンス表示またはリンク先GitHubリポジトリのライセンスがある場合は、その条件を優先します。引用・第三者資料・画像・商標等は本ライセンスの対象外です。 利用ポリシー

タイトルとURLをコピーしました