Add File Name to Existing Word Document

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 9 months ago.

  • Author
    Posts
  • #5117

    by jmcdade87 at 2012-09-17 07:15:49

    Hello all. I am new to scripting and my employer would like me to add the file path and name to the footer of every existing word document in our shared directory. I need help writing either a powershell script that can do the following:

    – Search a drive and all subfolders for all .doc and .docx documents
    – Create a footer
    – Add the path and file name to the footer
    – Save and close the document

    Thank you in advance for your help.

    by poshoholic at 2012-09-17 07:29:58

    Hi there,

    The easiest way for you to get help with such a task would be to share whatever script you have so far and indicate where you are running into difficulties. If your difficulty is in starting the script, then indicate that you're having trouble with the basics getting started and we'll be able to point you in the right direction. If you have a script started, then share that and let us know where you are getting stuck. I think taking that approach will help us help you more effectively.

    Thanks,

    by jmcdade87 at 2012-09-17 07:36:58

    Hi Poshoholic,

    Thank you for your response. So far I have the following:

    $path = "C:\FooterTest"
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
    $objWord = New-Object -ComObject "word.application"
    $objWord.visible = $false
    foreach($wd in $wordFiles)
    {
    $doc = $objWord.documents.open($wd.fullname)
    set-variable -name wdFieldFileName -option constant
    $a.Visible = $True
    $b = $a.Documents.Add()
    $c = $b.Sections.Item(1).Footers.Item(1).FieldFileName.Add($wdFieldFileName)
    $doc.Save()
    $objWord.Documents.Close()
    }
    $objWord.Quit()

    I set up a test folder where I basically created a bunch of blank word documents with different names. The script will open and close the documents but doesn't append the footer with the filename. Also, I am using word 2010 if that helps.

    by poshoholic at 2012-09-17 08:14:00

    Thanks, that helps. I was wondering if you had already figured out the COM object stuff to open the document and whatnot, and this shows me that you have. You're actually pretty close to your solution. Rather than work out the details directly here though, I did some searching based on what you're looking for and I think I found an article that will help you resolve this. Check out this link: http://www.tek-tips.com/viewthread.cfm?qid=1629555. It contains a function called Edit-Footer that someone uses to apply a field to a footer in a document, demonstrating how it needs to be set up properly when creating the field and applying it to the footer. See if you can leverage that example to get your script working. If not, come back with whatever hangup you have and then I can try to help you out more from there.

    by jmcdade87 at 2012-09-17 13:18:39

    Sorry for the late response, I got sidetracked. Anyway, when I run the script, I now recieve an error stating the documents are locked by me and is read only. Here's what I have so far:

    $path = "C:\FooterTest"
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
    $objWord = New-Object -ComObject "word.application"
    $objWord.visible = $false
    foreach($wd in $wordFiles)
    {
    $doc = $objWord.documents.open($wd.fullname)
    set-variable -name wdFieldFileName -option constant

    }

    param ([string]$Document)

    function Edit-Footer ([string]$Document) {
    add-type -AssemblyName "Microsoft.Office.Interop.Word"
    #Variables used
    set-variable -name wdFieldFileName -value 1 -option constant
    $Word = New-Object -comobject Word.Application
    $Word.Visible = $True
    #$Word.Visible = $False
    $OpenDoc = $Word.Documents.Open($Document)
    $c = $OpenDoc.Sections.Item(1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    $range1 = $openDoc.Sections.Item(1).Footers.Item(1).range

    $doc.Save()
    $objWord.Documents.Close()
    $objWord.Quit()
    }

    by poshoholic at 2012-09-17 15:46:12

    Do you have the "Read-only Recommended" setting enabled for Word 2010 on your system? See this post for more details: http://cybertext.wordpress.com/2010/07/14/word-2007-document-goes-to-read-only-for-no-reason/#.

    by jmcdade87 at 2012-09-18 07:04:48

    No, I do not have read only recommended enabled.

    by poshoholic at 2012-09-18 07:32:52

    Ok, I think I get what's going on. Looks like you're opening the documents, then calling the Edit-Footer function while those documents are already open (and therefore getting a read-only copy). Try rearranging your script to something like this:
    $path = "C:\FooterTest"
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
    $word = New-Object -ComObject Word.Application
    $word.Visible = $true # Remove this line later to keep the application invisible; when testing though, better to work with a visible application
    foreach ($wd in $wordFiles)
    {
    $doc = $word.documents.open($wd.fullname)
    set-variable -name wdFieldFileName -value 1 -option constant

    $c = $doc.Sections.Item(1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    #$range1 = $doc.Sections.Item(1).Footers.Item(1).range

    $doc.Save()
    $doc.Close()
    }
    $word.Quit()

    Note that this should add page numbers to the footer, not the file name. It's a stepping stone to make sure you're headed in the right direction. Also, since this will do work with a visible word document, I recommend you step through this line by line in a debugger to see what happens as the script runs. That will allow you to look at the document while it is being updated.

    by jmcdade87 at 2012-09-18 08:09:23

    I tried running the script you poseted and it worked for the first word doc in my folder but not the rest. It seems I'm still having an issue with Read-Only protection:

    Method invocation failed because [System.__ComObject] doesn't contain a method named 'open'.
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : InvalidOperation: (open:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:13 char:34
    + $range1 = $doc.Sections.Item < <<< (1).Footers.Item(1).range
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Quit" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:17 char:16
    + $word.Quit < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : InvalidOperation: (open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:13 char:34
    + $range1 = $doc.Sections.Item < <<< (1).Footers.Item(1).range
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Quit" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:17 char:16
    + $word.Quit < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : InvalidOperation: (open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:13 char:34
    + $range1 = $doc.Sections.Item < <<< (1).Footers.Item(1).range
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Quit" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:17 char:16
    + $word.Quit < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : InvalidOperation: (open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:13 char:34
    + $range1 = $doc.Sections.Item < <<< (1).Footers.Item(1).range
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Quit" with "3" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
    At C:\FooterTest\test2.ps1:17 char:16
    + $word.Quit < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    by jmcdade87 at 2012-09-18 08:12:04

    I had put the close doc inside of the funtion and forgot. This is what I'm getting with the exact code you provided. It is still giving me the read only prompt. after the first document.

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    Exception calling "Open" with "1" argument(s): "Command failed"
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The object invoked has disconnected from its clients. (Exception from H
    RESULT: 0x80010108 (RPC_E_DISCONNECTED))"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The object invoked has disconnected from its clients. (Exception from
    HRESULT: 0x80010108 (RPC_E_DISCONNECTED))"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Open" with "1" argument(s): "Command failed"
    At C:\FooterTest\test2.ps1:9 char:33
    + $doc = $word.documents.open < <<< ($wd.fullname)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    You cannot call a method on a null-valued expression.
    At C:\FooterTest\test2.ps1:12 char:29
    + $c = $doc.Sections.Item < <<< (1).Footers.Item(1).PageNumbers.Add($wdFieldFileName)
    + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Save" with "0" argument(s): "The object invoked has disconnected from its clients. (Exception from H
    RESULT: 0x80010108 (RPC_E_DISCONNECTED))"
    At C:\FooterTest\test2.ps1:15 char:15
    + $doc.Save < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Exception calling "Close" with "3" argument(s): "The object invoked has disconnected from its clients. (Exception from
    HRESULT: 0x80010108 (RPC_E_DISCONNECTED))"
    At C:\FooterTest\test2.ps1:16 char:16
    + $doc.Close < <<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Set-Variable : Cannot overwrite variable wdFieldFileName because it is read-only or constant.
    At C:\FooterTest\test2.ps1:10 char:18
    + set-variable < <<< -name wdFieldFileName -value 1 -option constant
    + CategoryInfo : WriteError: (wdFieldFileName:String) [Set-Variable], SessionStateUnauthorizedAccessExcep
    tion
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

    by jmcdade87 at 2012-09-18 08:16:24

    I take it back. Aparently I had one that had the footer in it so it seems like that was hanging it up. Once I cleared all of the footers in the documents it ran fine. Now I can try to change this to the file name!

    by poshoholic at 2012-09-18 08:26:07

    Excellent, that's great.

    You can also do a few other things to improve this:
    1. Move the Set-Variable call before the foreach loop to get rid of the error about being unable to overwrite it because it is constant.
    2. When you get errors, step through with a debugger and confirm that assumptions are valid and make sure you know where it is hanging up. For example, when you iterate through the loop, does $wd.FullName contain the value you expect every time? Does the document open? What happens next? What if you try to perform the different steps manually, opening a document, setting the page number in the footer, then saving/closing the document, then opening another document, etc....does that work?
    3. As a safeguard I would probably nullify the $doc variable at the end of the foreach loop (i.e. add $doc = $null right after $doc.Close()).
    4. To properly grow this script and use it on a regular basis, it should have error handling. Use Write-Verbose liberally in the script to verify assumptions so that you can invoke the script using -Verbose later and get relevant details. After you try to open the document, if it is not open (i.e. if ($doc -eq $null)), you should probably use the continue keyword to continue to the next document (no point trying to do stuff with a document that didn't open properly). That sort of thing will go a long way to having a script that you can use and reuse over time while being able to deal with unexpected issues that come up.

    by jmcdade87 at 2012-09-18 08:48:28

    So for item "4", would that look something like

    if($doc -eq $null) { $doc -eq $null; continue }

    I greately appreciate all of the help you've given me. One other thing, I see I will need to change "PageNumbers" to the necessary filename property but I don't know what it is or how I can search to figure it out. Could point me in the right direction to finding what can be used?

    by poshoholic at 2012-09-18 08:55:15

    For items 3 and 4 it would require two things:

    1. At the beginning of the foreach loop, right after you call $word.Documents.Open:
    if ($doc -eq $null) {continue}
    2. At the end of the foreach loop, right before the closing curly brace:
    $doc = $null
    For the FileName field, I would need to search for that and don't have time right now. I'll see if I have some time later today.

    by jmcdade87 at 2012-09-18 08:58:54

    Not a problem thank you very much. I'm going to continue searching to see if I can figure it out as well.

    by jmcdade87 at 2012-09-20 05:03:32

    I can't figure this one out...

    by poshoholic at 2012-09-20 10:22:39

    I think I got it. Fields in Word document automation are identified by constant numeric values. The values for the various fields are identified in this document: http://msdn.microsoft.com/en-us/library ... 92211.aspx.

    You want to add the filename field, which is called wdFieldFileName, and which has a value of 29. I would presume then, that when you create the constant variable called wdFieldFileName, you should give it a value of 29 instead of a value of 1. That's easy enough. But then there is a trick in how you can add a field to a footer. I figured out this logic, and it looks like this:

    $path = 'C:\FooterTest'
    Set-Variable -Name wdFieldFileName -Value 29 -Option constant
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -Include *.doc, *.docx -Recurse
    $word = New-Object -ComObject Word.Application
    $word.Visible = $true # Remove this line later to keep the application invisible; when testing though, better to work with a visible application
    foreach ($wd in $wordFiles)
    {
    $doc = $word.documents.open($wd.fullname)

    [void]$doc.Fields.Add($doc.Sections.Item(1).Footers.Item(1).Range, $wdFieldFileName)

    $doc.Save()
    $doc.Close()
    }
    $word.Quit()

    by jmcdade87 at 2012-09-20 10:27:32

    I came up with this and it seems to be working:

    $path = "C:\FooterTest"
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse

    $word = New-Object -ComObject Word.Application
    #$word.Visible = $true # Remove this line later to keep the application invisible; when

    testing though, better to work with a visible application

    set-variable -name wdFieldFileName -value 1 -option constant

    foreach ($wd in $wordFiles)
    {
    $doc = $word.documents.open($wd.fullname)
    if ($doc -eq $null) {continue}

    $section = $doc.Sections.Item(1)
    $footer = $section.Footers.Item(1)
    $footer.Range.Text = $wd.fullname

    $doc.Save()
    $doc.Close()
    $doc = $null
    }
    $word.Quit()

    by poshoholic at 2012-09-20 10:32:47

    That will work, but if you change the file name later then the footer won't be in sync. If that's not a big deal, that was what I would have recommended if I couldn't find the field that you wanted to add.

    by jmcdade87 at 2012-09-20 10:39:56

    Good call, I didn't think of that. I appreciate the help greatly!

    by jmcdade87 at 2012-09-20 10:57:51

    So I tried your method and it only added the file name to the footer and not the whole path.

    by poshoholic at 2012-09-20 11:21:54

    You're right. That's an additional option that needs to be added when the field is added to the document, like this:

    $path = 'C:\FooterTest'
    Set-Variable -Name wdFieldFileName -Value 29 -Option constant -Force -ErrorAction SilentlyContinue
    Add-Type -AssemblyName Microsoft.Office.Interop.Word
    $wordFiles = Get-ChildItem -Path $path -Include *.doc, *.docx -Recurse
    $word = New-Object -ComObject Word.Application
    $word.Visible = $true # Remove this line later to keep the application invisible; when testing though, better to work with a visible application
    foreach ($wd in $wordFiles)
    {
    $doc = $word.documents.open($wd.fullname)

    $field = $doc.Fields.Add($doc.Sections.Item(1).Footers.Item(1).Range, $wdFieldFileName, '\p')

    $doc.Save()
    $doc.Close()
    }
    $word.Quit()

    by jmcdade87 at 2012-09-20 11:26:22

    You're the man. Consider this solved.

    by poshoholic at 2012-09-20 12:04:13

    Excellent, glad it worked out for you!

You must be logged in to reply to this topic.