M365関連 プログラム 技術

PowerShellでファイル読み込み(PowerPoint)

PowerPointファイルを読み込んでみる

読み込むファイルの種類

今回、紹介するファイル読み込みは以下の拡張子が対象です
・PowerPointファイル(.ppt / .pptx / .pptm)

前提条件

Word、Excel、PowerPointといったOfficeファイル形式を読み込む際は
実行環境に読み込み対象とするWord、Excel、PowerPointといったデスクトップアプリが
あらかじめインストールされており、ライセンス等の認証が完了している必要があります
今回紹介する方法がそのアプリの機能を使用しているためです

実際に読み込む

PowerPointファイルを開く

PowerPointに対して処理する際にパスワードがかかっている場合にパスワードを使用して開くようにしていますもし、パスワードがかかっていない場合はパスワードの値は無視して開くようになっています
PowerPointだけOpenメソッドにパスワードを渡す場所がないため、PowerPointのパスの後ろにくっつけて渡す形になります

$pptx = New-Object -ComObject PowerPoint.Application
$readPass = "PowerPointを開く際に使用するパスワード"
$pptOpen = "PowerPointファイルパス::" + $readPass
$slides = $pptx.presentations.Open($pptOpen)

PowerPointファイル内を読み込む

PowerPoint内で各スライドに設定されているハイパーリンクやテキストボックス、図形等に記載されているテキストを読み込んでいます

$slides.Slides | ForEach-Object {
    
    $_.Hyperlinks | ForEach-Object {
        Write-Host $_.Address
    }

    $_.Shapes | ForEach-Object {

        if($_.HasTextFrame){
            Write-Host $_.TextFrame.TextRange.text
        }
        elseif($_.HasTable){
            $_.Table.Columns | ForEach-Object {
                $_ | ForEach-Object {
                    Write-Host $_.Shape.TextFrame.TextRange.text
                }
            }
        }elseif($_.HasChart){
            if($_.Chart.HasTitle){
                Write-Host $_.Chart.Title
            }
        }
        elseif($_.HasSmartArt){
            $_.SmartArt.Nodes | ForEach-Object {
                Write-Host $_.TextFrame2.TextRange.text
            }
        }
        #グループの場合(msoGroupの値は6)
        elseif($_.Type -eq 6){
            $shp.GroupItems | ForEach-Object {
                if($_.HasTextFrame){
                    Write-Host $_.TextFrame.TextRange.text
                }
            }
        }
    }
}

開いたPowerPointを閉じる

以下はPowerPointを読み込んだ後始末の決まった作法みたいなものになるのでそのまま使用してください。PowerPointを読み込むときに使用したメモリーを開放したり、PowerPointタスクを終了させたりしています

if($slides){
    $slides.Close()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($slides) | Out-Null
    $slides = $null
    Remove-Variable -Name slides -ErrorAction SilentlyContinue
}

[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.GC]::Collect()

if($pptx){
    $pptx.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($pptx) | Out-Null
    $pptx = $null
    Remove-Variable -Name pptx -ErrorAction SilentlyContinue
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    [System.GC]::Collect()
}

最後に

今回はPowerPoint内の様々な箇所からのテキスト読み込みをしてみました
WordやExcelの読み込みも別の記事で紹介します
全体のコードはGitHubにアップしているので参考になれば

サンプル
BlogSampleCodeProjects/PowerShell_FileLoad/PowerPointFileLoad.ps1 at main · nasuton/BlogSampleCodeProjects · GitHub
BlogSampleCodeProjects/PowerShell_FileLoad/PowerPointFileLoad.ps1 at main · nasuton/BlogSampleCodeProjects · GitHub

Project for sample code used in the blog.(Blogで記載しているサンプルコード ...

続きを読む

-M365関連, プログラム, 技術
-,