如何编写PowerShell脚本批量删除PowerPoint文件的文档属性?
错误排查
- 符号错误:代码中使用了中文双引号
“”,PowerShell无法识别,需要替换为英文双引号"" - 变量初始化顺序错误:在实例化
$objPoint对象之前就对其Visible属性赋值,会触发空对象引用错误 - 对象模型不匹配:PowerPoint的COM对象没有
Workbooks集合,对应的演示文稿集合是Presentations,打开返回的对象为Presentation而非Workbook - 枚举值错误:PowerPoint的
PpRemoveDocInfoType枚举的全量删除属性值为ppRDIAll,而非Excel用的xlRDIAll - 缺少COM对象释放逻辑:处理完成后未释放COM对象,会导致PowerPoint进程残留在后台
修正后可运行代码
$path = "c:\fso" Add-Type -AssemblyName Microsoft.Office.Interop.PowerPoint $PpRemoveDocType = "Microsoft.Office.Interop.Powerpoint.PpRemoveDocInfoType" -as [type] # 已新增对新版PPT格式的匹配,不需要可删除对应的后缀规则 $pointFiles = Get-ChildItem -Path $path -Include *.pot, *.ppt, *.pps, *.pptx, *.potx, *.ppsx -Recurse # 先实例化对象再设置属性 $objPoint = New-Object -ComObject powerpoint.application $objPoint.Visible = [Microsoft.Office.Core.MsoTriState]::msoFalse foreach($file in $pointFiles) { "Removing document information from $($file.FullName)" # PowerPoint用Presentations集合打开文件 $presentation = $objPoint.Presentations.Open($file.FullName, [Microsoft.Office.Core.MsoTriState]::msoFalse) # 使用PowerPoint对应的枚举值 $presentation.RemoveDocumentInformation($PpRemoveDocType::ppRDIAll) $presentation.Save() $presentation.Close() # 释放单文件对象 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($presentation) | Out-Null } $objPoint.Quit() # 释放PowerPoint应用对象 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objPoint) | Out-Null Remove-Variable objPoint
内容的提问来源于stack exchange,提问作者Zeontay Anthony
相关产品推荐
相关产品推荐

