
PowerShellで
・PDFにパスワードを設定する
できます!

PowerShellから
・無料ツール「QPDF」を呼び出す
ことで実現します!
※無料ツール「QPDF」の実行ファイルの取得(ダウンロード)が必要です。
QPDFの取得(ダウンロード)
以下の記事の「QPDFの取得(ダウンロード)」をご確認ください。
コード
ここでは例として、
・デスクトップ配下のPDF「サンプル.pdf」を
・パスワードありのPDFとして出力
します。

# qpdfの実行ファイルのパス
$qpdfExePath = "C:\Users\lunch\Desktop\qpdf-11.6.3-mingw64\bin\qpdf.exe"
# パスワード設定対象のPDFのパス
$targetPdfFilePath = "C:\Users\lunch\Desktop\サンプル.pdf"
# 出力するPDF(パスワードあり)のパス
$passwordPdfFilePath = "C:\Users\lunch\Desktop\パスワード付きファイル.pdf"
# PDFに設定するパスワード
$pdfPassword = "password12345"
# 7z.exeを実行する際の引数を組み立て
$arg=" --encrypt " + $pdfPassword + " " + $pdfPassword + " 256 -modify=none --print=full -- " + $targetPdfFilePath + " " + $passwordPdfFilePath
$ws = New-Object -ComObject Wscript.Shell
# PDF(パスワードあり)を出力
$process = Start-Process -FilePath $qpdfExePath -ArgumentList $arg -Wait -WindowStyle Hidden -PassThru
if ($process.ExitCode -eq 0) {
$ws.popup("正常終了しました。")
} else {
$ws.popup("異常終了しました。")
}
実行結果
PDFにパスワードを設定できました。


出力されたPDFファイル(パスワードあり)を開くと、パスワードの入力を求められます。

パスワードを入力すると、ちゃんと開けました。
