2014年12月18日木曜日

改訂番号を含めてWordのプロパティ値を削除する(メモ)


近いうちに整形する。

---

# 作業ディレクトリの作成
$tmpDir = "C:\ps-test\tmp"
New-Item $tmpDir -ItemType Directory

# ターゲットファイル(docx)
$targetFile = "C:\ps-test\2.docx"

# オリジナルのファイル名のみ抽出
$originalFileName = Split-Path $targetFile -Leaf
# オリジナルの格納ディレクトリのみ抽出
$originalFileDir = Split-Path $targetFile -Parent

# zipファイル名の生成
$tmpFile = ($targetFile -replace ".docx$", ".zip")

# リネーム( docx => zip )
# (Shell.Applicationからアーカイブ操作するため)
Rename-Item -Path $targetFile $tmpFile

# シェルオブジェクトの作成
$shell = New-Object -Com Shell.Application

$shell.NameSpace($tmpFile).Items() | ?{ $_.Name -eq "docProps" } | %{$_.GetFolder.items()} | ?{$_.Name -eq "core.xml"} | %{$_.Name;$shell.NameSpace($tmpDir).movehere($_)}

# 作業用 core.xml のパス生成
$coreFile = ($tmpDir + "\" + "core.xml")

$contentCoreFile = Get-Content $coreFile
$contentCoreFile =[regex]::Replace($contentCoreFile, "<dc\:title>[\s\S]*<\/dc\:title>", "<dc:title>testT</dc:title>")
$contentCoreFile =[regex]::Replace($contentCoreFile, "<dc\:creator>[\s\S]*<\/dc\:creator>", "<dc:creator>Creator</dc:creator>")
$contentCoreFile =[regex]::Replace($contentCoreFile, "<cp\:lastModifiedBy>[\s\S]*<\/cp\:lastModifiedBy>", "<dc:creator></dc:creator>")
$contentCoreFile =[regex]::Replace($contentCoreFile, "<cp\:revision>[\s\S]*<\/cp\:revision>", "<cp:revision></cp:revision>")
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
[System.IO.File]::WriteAllLines($coreFile, $contentCoreFile, $Utf8NoBomEncoding)

# 編集後のcore.xmlをzipの中へ移動
$shell.NameSpace($tmpFile + "\docProps").movehere($coreFile)

Start-Sleep -Milliseconds 500

If( Test-Path $coreFile ){
  Write-Host "remove.."
  Remove-Item $coreFile
}

$shell = $nothing

# リネーム( zip => docx )
# (zipから元に戻す)
Rename-Item -Path $tmpFile $targetFile

Remove-Item $tmpDir

0 件のコメント:

コメントを投稿