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

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
ライセンス:本記事のテキスト/コードは特記なき限り CC BY 4.0 です。引用の際は出典URL(本ページ)を明記してください。
利用ポリシー もご参照ください。

コメント

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