0

so I use PDFTK to bulk password generate and protect pdfs and store the name and password in an Excel file. But every time there is a [ ] in the file name, the file is skipped/the script doesn't work.

$password_file="output\passwords.xlsx"
Remove-Item $password_file -ErrorAction Ignore

Get-ChildItem "input\*.pdf" | % {
$inp_file=$_
$out_file="output\" + (Get-Item $inp_file).Basename + ".pdf"

#  Create pasword and write to password file
$tmp_password_file="output\tmp_pwd.txt"
Remove-Item $tmp_password_file -ErrorAction Ignore
$password=-join ("!?@#$%^&0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".tochararray() | ForEach-Object {[char]$_} | Get-Random -Count 16)
$password > $tmp_password_file

# Read the password from the (just created) password file
$pwd=Get-Content $tmp_password_file

# Encrypt the pdf file
pdftk $inp_file output $out_file user_pw $pwd

# write pdf filename and password to file
$zz=(Get-Item $inp_file).Basename + "," + $pwd.ToString()
Add-Content $password_file $zz
}

How can I fix this? Thanks in advance!

Akshay KB
  • 1
  • 2
  • 3
    Did you check for: [`PowerShell file square bracket`](https://stackoverflow.com/search?q=PowerShell+file+square+bracket)? – iRon Sep 04 '21 at 10:32
  • 1
    As aside.. you already have the FileInfo object from `Get-ChildItem` (you even store that in `$inp_file`), so you don't need to do that several times more with `(Get-Item $inp_file).Basename`. `$_.BaseName` or in your case `$inp_file.BaseName` is enough – Theo Sep 04 '21 at 11:21
  • 3
    As 2nd aside.. `$pwd` is an [automatic variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7#pwd). You should not use that as self-defined variable name. – Theo Sep 04 '21 at 13:04
  • 1
    Does this answer your question? [How can I make PowerShell handle \[ or \] in file name well?](https://stackoverflow.com/questions/57755417/how-can-i-make-powershell-handle-or-in-file-name-well) (use: `-LiteralPath`) – iRon Sep 04 '21 at 13:47

0 Answers0