Search code examples
powershellms-officems-publisher

Replacing Text in Microsoft Publisher Using Powershell


My HR team asked if I could help them generate new business cards for all of our employees. They have a Publisher file and I am trying to replace the text in. I've written all the portions that pull the info from AD and the looping mechanism but I cannot get the text replacement to function. I've done something like this in Microsoft Word before using the Find.Execute Method from Word. That was straightforward as I just fed the method my arguments and it worked.

This time though, I am trying to use the FindReplace Object from Publisher. I think I am misusing it but I'm not sure how. My code is below and any input would be appreciated. Sorry if this is a silly question, but I'm stil relatively new to PowerShell and .NET.

$Document = "C:\Test\testcard.pub"

$Publisher = New-Object -comobject Publisher.Application  

$OpenDoc = $Publisher.Open($Document)

$OpenDoc.Find.Clear()
$OpenDoc.Find.FindText = "Jane"
$OpenDoc.Find.ReplaceWithText = "John"
$OpenDoc.Find.ReplaceScope = $pbReplaceScopeAll
$OpenDoc.Find.Execute() 

$OpenDoc.Save()
$OpenDoc.Close()
$Publisher.quit()

Solution

  • I think $pbReplaceScopeAll isn't defined. Even though it looks like it should in the documentation. The documentation uses Visual Basic, a language which implicitly creates variables from enumerations.

    PowerShell doesn't offer this feature, so you'll have to directly reference the enumeration value you need. This might work:

    $OpenDoc.Find.ReplaceScope = [Publisher.PbReplaceScope]::pbReplaceScopeAll
    

    If that doesn't work, it looks like the pbReplaceScopeAll value is 2, so you could define $pbReplaceScopeAll yourself:

    $pbReplaceScopeAll = 2
    ## snip
    $OpenDoc.Find.ReplaceScope = $pbReplaceScopeAll