如何让PowerShell脚本排除受密码保护的.doc文件再删除其余文件?
解决PowerShell脚本中排除密码保护.doc文件不被删除的问题
修改思路
- 记录成功完成转换的.doc文件路径,仅对这些文件执行删除操作
- 添加错误捕获逻辑,处理密码保护文件打开失败的情况
- 修正原脚本中的语法错误
修改后的完整脚本
$invocation = (Get-Variable MyInvocation).Value $curr_path = Split-Path -parent $MyInvocation.MyCommand.Path $doc_app = New-Object -ComObject Word.Application $doc_app.DisplayAlerts = "wdAlertsNone" # 提前设置弹窗静默,避免干扰 $successfullyConverted = @() # 存储成功转换的文件路径 Get-ChildItem -Path $curr_path -Recurse -Include *.doc | ForEach-Object { $docFile = $_ $docFile.IsReadOnly = $false Write-Host "Working on-> $($docFile.FullName) ..." try { # 尝试打开文件,密码错误会触发异常 $document = $doc_app.Documents.OpenNoRepairDialog( $docFile.FullName, $false, # 不确认转换 $false, # 只读模式关闭 $false, # 不添加到最近文件 "ignorepass" # 无效密码占位符 ) # 生成docx路径(用Join-Path避免路径分隔符错误) $docx_filename = Join-Path -Path $docFile.DirectoryName -ChildPath "$($docFile.BaseName).docx" $Format = [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatXMLDocument $document.SaveAs($docx_filename, $Format) $document.Close() $successfullyConverted += $docFile.FullName # 记录成功转换的文件 Write-Host "Successfully converted: $($docFile.FullName)" } catch { Write-Warning "Failed to process $($docFile.FullName) - likely password protected or corrupted" # 可通过匹配错误消息精准判断密码保护问题: # if ($_.Exception.Message -match "password") { Write-Warning "Password protected file skipped" } continue # 跳过当前文件,不加入删除列表 } } # 清理Word进程,避免残留 $doc_app.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc_app) | Out-Null [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() # 仅删除成功转换的文件 if ($successfullyConverted.Count -gt 0) { $successfullyConverted | Remove-ItemSafely Write-Host "Deleted $($successfullyConverted.Count) successfully converted .doc files" } else { Write-Host "No files to delete" }
关键改动说明
- 新增成功文件记录数组:
$successfullyConverted用来存储所有完成转换的.doc文件路径,彻底避免误删未处理的密码保护文件 - 添加错误捕获(try/catch):打开密码保护的.doc文件时会触发异常,进入catch块后直接跳过该文件,不加入删除列表
- 修正路径生成逻辑:用
Join-Path替代字符串拼接,解决路径分隔符缺失导致的转换失败问题 - 优化弹窗设置:将静默弹窗配置移到循环外,减少重复操作
- 精准删除逻辑:最后仅对确认转换成功的文件执行删除操作,完全排除未处理的密码保护文件
内容的提问来源于stack exchange,提问作者reape185
相关产品推荐
相关产品推荐

