首页 > 解决方案 > 如何使用 Powershell 删除现有的 Word Doc 水印?

问题描述

我需要使用 PowerShell 从现有 Word 文档中删除水印。我正在尝试将 Word 宏记录器的结果转换为 PowerShell,但出现“[System.__ComObject] 不包含名为 'Shapes' 的方法”错误。任何帮助表示赞赏。PS代码如下。

$Word=New-Object -ComObject "Word.Application"
$wdSeekPrimaryHeader = 1
$Doc=$Word.Documents.Open("C:\Users\mynamehere\Downloads\andSuch\SampleDoc1.docx")
$Selection=$Word.Selection
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$Selection.HeaderFooter.Shapes("PowerPlusWaterMarkObject357476642").Select
$Selection.ShapeRange.Delete
$Doc.Save()
$Doc.Close()
$Word.Quit()

标签: powershellms-word

解决方案


显示您的代码?

简单搜索您的用例“PowerShell 和 Microsoft 单词删除水印”将为您提供一个列表,甚至是您所追求的完整脚本。例如,这个是关于添加水印的。当然删除是,你会颠倒逻辑。

如何使用 PowerShell 为 Word 文档添加水印

#Relevant files
$File = $args[0]
$WM = $args[1]

#Open document in Word
$Word = New-Object -ComObject Word.Application
$Word.Visible = $False
$Doc  = $Word.Documents.Open($File)

#Insert Watermark
Function Watermark
{
    #Create rectangle
    $Shape = $args[0].Shapes.AddShape(1,0, 0, 500, 125)

    #Fill rectanlge with watermark image
    $PicFill = $Shape.Fill.UserPicture($args[1])

    #Hide rectangle lines
    $Shape.Line.Visible = $False

    #Set transparency of watermark
    $Shape.Fill.Transparency = .8

    #Center watermark on width of page
    $Shape.Left = -999995

    #Center watermark on height of page (This was guess and checked)
    $Shape.Top = 250

    #Rotate watermark
    #Rotation rarely works when Word is not visible.  Command left here for reference.
    $Shape.Rotation = 315
}

#Only on 1st Page
#Watermark $Doc $WM

#On all Pages
#Determine number of pages in document
$Bind = 'System.Reflection.BindingFlags' -as [type]
$Doc.Repaginate()
$Prop = $Doc.BuiltInDocumentProperties(14)
$Pages = [System.__ComObject].invokemember('Value', $Bind::GetProperty, $null, $Prop, $null)

#Start at 0 to include any cover pages
For ($i = 0; $i -le $Pages - 1; $i ++)
{
    #Change pages
    $Word.Selection.GoTo(1,2,$null,$i)

    #Apply watermark
    Watermark $Doc $WM
}

#Check version of Word installed and save changes
$Version = $Word.Version
If ($Version -eq '16.0' -Or $Version -eq '15.0') {
    $Doc.Close($True)  
}
ElseIf ($Version -eq '14.0') {
    $Doc.Close([ref]$True)
}

#Exit Word
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)

#Cleanup
Remove-Variable Word

你也可以,只是——

  1. 打开任何带水印的 Word 文档。
  2. 启动 Word 宏记录器。
  3. 在 Word 中做你想做的事。
  4. 完成后停止录音机。
  5. 导出宏代码。
  6. 转换宏 VBA 代码以用于 PowerShell。

推荐阅读