ポワポ・ファイルからドキュメント情報を除去する PowerShellスクリプト

参考にしたのはPowershell script for removing personal info from Word, Excel, and Powerpoint docs. | yet another scripting blog。このスクリプトはWord, Excel, PowerPointとオフィス・ファイルは全部対応しているので、必要に応じて参照すると良いと思う。

下ではPowerPointファイルに限定して、かつカレントディレクトリにあるファイルを全部処理するようにしてある。 スクリプト自身のエラー表示なども省略した。

一番ハマったのは

$PpRemoveDocType = "Microsoft.Office.Interop.PowerPoint.PpRemoveDocInfoType" -as [type]
$PpRemoveDocType::ppRDIAll

で「列挙値が無効」のようなエラーが出ること。

仕方がないので、PpRemoveDocInfoType 列挙 (PowerPoint) | Microsoft Learnを参照して、変数名ではなく値(今の場合は99)を直接ブチ込んだ。

Add-Type -AssemblyName Microsoft.Office.Interop.Powerpoint

もエラーを吐くが、

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.PowerPoint")

とすればエラーは出さなくなる。これは下のスクリプトでは省略している。

# カレントディレクトリのpptxのdocument information を削除する
# 参考にしたページ: https://journeymblog.wordpress.com/2017/01/10/powershell-script-for-removing-personal-info-from-word-excel-and-powerpoint-docs/
$errorlinespowerpoint=@()

$folderPath = Get-Location
Write-Host "Processing folder: " $folderPath
$powerpointfiles = Get-ChildItem -Path $folderPath -include *.ppt, *.pptx -Recurse

function TestFileLock ($FilePath){
    $FileLocked = $false
    $FileInfo = New-Object System.IO.FileInfo $FilePath
    trap {Set-Variable -name Filelocked -Value $true -scope 1; continue}
    $FileStream = $FileInfo.Open( [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None )
    if ($FileStream) {$FileStream.Close()}
    $FileLocked
}

if ($powerpointfiles -ne $null) {
    $objpowerpoint = New-Object -ComObject Powerpoint.Application
    Write-Host "Processing Powerpoint files"
    foreach($obj in $powerpointfiles) {
        if (TestFileLock $obj.FullName) {
            Write-Host "File '$($obj.Name)' is locked" -ForegroundColor Red
            $errorlinespowerpoint+="'$($obj.fullname)' is locked"
        }
        else {
        Write-Host "Processing file: " $obj.Name
            $documents=$objpowerpoint.Presentations.Open($obj.FullName, $false, $null, $false)
        #    $documents.RemoveDocumentInformation($PpRemoveDocType::ppRDIAll)
            $documents.RemoveDocumentInformation(99)
            $documents.Save()
            $documents.Close()
            Write-Host "File '$($obj.Name)' metadata cleared" -ForegroundColor Green
        }
    }
    $objpowerpoint.Quit()
    $documents=$null
}
try {
    $objpowerpoint.Quit()
} catch {write-host “Killing remaining active applications”}

Write-Host "Powerpoint files $($powerpointfiles.Count), Errors: $($errorlinespowerpoint.count)" -ForegroundColor Red
Write-Host "Error files:" $errorlinespowerpoint

自分はWindows系の処理は疎くて分からないことだらけで、とても手間取った。 pptxを開かずに処理したかったので、VBAで書くわけにいかず、VBSは先がないということで、PowerShellで書くのが正しいのだろうと思う。

Adsense広告