Taylohtio/_Scripts/SecurePdfFiles/SecurePdfFiles.ps1

88 lines
2.3 KiB
PowerShell

[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 1)]
[string]$sourcePath,
[Parameter(Mandatory = $True, Position = 2)]
[string]$targetPath,
[Parameter(Mandatory = $True, Position = 3)]
[string]$password
)
$enginePath = "C:\Program Files (x86)\PDFtk\bin\pdftk.exe"
function EncryptFiles($path = $pwd, [string[]]$exclude)
{
foreach ($item in Get-ChildItem $path)
{
if ($exclude | Where {$item -like $_})
{
continue
}
if (Test-Path $item.FullName -PathType Container)
{
$target = $item.FullName.Replace($sourcePath, $targetPath)
if (!(Test-Path $target))
{
New-Item -ItemType directory -Path $target | Out-Null
}
EncryptFiles $item.FullName $exclude
}
else
{
if ($item.Extension.Equals(".pdf"))
{
$oldItem = $item.FullName
$newItem = $oldItem.Replace("$sourcePath", "$targetPath")
& "$enginePath" $oldItem output $newItem owner_pw $password 2>&1 | Out-Null
if ($LASTEXITCODE -eq 1)
{
Write-Host "An error occured while processing file: $item" -ForegroundColor Red
$error
}
else
{
Write-Host "Successfully secured file: $item" -ForegroundColor Green
}
}
}
}
}
Write-Host "PDF encryption script" -ForegroundColor Green
if (!(Test-Path -Path $enginePath))
{
Write-Host "Error: pdftk engine not installed" -ForegroundColor Red
return
}
if (-not $sourcePath)
{
Write-Host "Error: please provide source directory" -ForegroundColor Red
return
}
if (!(Test-Path $sourcePath))
{
Write-Host "Error: source directory does not exist"
return
}
$sourcePath = (Get-Item -Path $sourcePath).FullName
if (-not $targetPath)
{
Write-Host "Error: please provide target directory" -ForegroundColor Red
return
}
if (-not $sourcePath.EndsWith("\"))
{
$sourcePath = $sourcePath + "\";
}
if (-not $targetPath.EndsWith("\"))
{
$targetPath = $targetPath + "\";
}
EncryptFiles $sourcePath
Write-Host "All done" -ForegroundColor Green