【问题标题】:Powershell find and move password protected PDF filesPowershell 查找和移动受密码保护的 PDF 文件
【发布时间】:2021-11-26 18:46:16
【问题描述】:

我正在编写一个脚本来识别文件夹中受密码保护的 pdf 文件。如果 pdf 受密码保护,那么它将将该文件夹以及所有文件和子文件夹移动到另一个文件夹。我可以让脚本与副本一起正常工作,但似乎正在读取“加密”文件的流式阅读器正在锁定文件,阻止我移动文件。我一直在尝试关闭流式阅读器的方法,但到目前为止没有任何效果。任何帮助将不胜感激。

$Source = 'sourcefolder'
$Dest = 'Destinationfolder'
        
Get-ChildItem -Path $Source -Directory |
ForEach-Object {
    If (Get-ChildItem -Path $_.FullName -filter *.pdf | where { 
            $_.OpenText().ReadToEnd().Contains("Encrypt") -eq $true }) {
        
        Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose
    }
}

【问题讨论】:

    标签: powershell encryption passwords streamreader opentext


    【解决方案1】:

    您需要在离开Where-Object 块之前处理掉流阅读器:

    ... |Where {
      try {
        ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt")
      }
      finally {
        if($reader){ $reader.Dispose() }
      }
    }
    

    在现有脚本的上下文中:

    Get-ChildItem -Path $Source -Directory | ForEach-Object {
      if (Get-ChildItem -Path $_.FullName -filter *.pdf | Where-Object { 
          try {
            ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt")
          }
          finally {
            if ($reader) { $reader.Dispose() }
          }
        }) {
            
        Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose
      }
    }
    

    【讨论】:

    • 我在放置 if 语句的结尾 ) 时遇到问题。
    • Get-ChildItem -Path $Source -Directory | ForEach-Object{ If (Get-ChildItem -Path $_.FullName -filter *.pdf | where { try{ ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt") } finally { if ($reader){ $reader.Dispose() } }} Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose }
    • @MichaelMoore 我已经用完整上下文中的示例更新了答案。我还强烈建议使用具有适当语法突出显示的编辑器(vscode 的 PowerShell 扩展非常好),如果应该更容易发现:)
    • 成功了,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多