Microsoft Windows Server are very great products to work with. And,... server administrators and operators do not like to do stupid work or repeating tasks. That's why I have made this category, to share my most favorite general scripts that I often use. This is not a scripting site, there are many more and better sites available for that. These scripts and tips are just handy for common, migrations and daily use. So, the initially set up was for my own references, but now I share it with you. Enjoy it !! Due to the fact that a big percentage of visitors of this page are international based, this article is in the english language.


The problem:
Migration of a lot of data into a new environment, new company policies, new domainname, results in a very slow start of Word documents as they are trying to resolve the (UNC) path, that is saved within the documents, but that no longer exists. It queries the DNS path, looking for the saved destination, but eventually times out, because the template path cannot be resolved. This behaviour can be recognized by the long display of contacting path-name and manually by checking the template path from within the document causing the issue. Both examples are shown in the pictures below.
Slow start of Word documents trying to resolve non-existing template path - www.oostdam.info Picture01
Slow start of Word documents trying to resolve non-existing template path - www.oostdam.info Picture02









     

This can be very troubling for end users, who will relate slow starting Word issues to your IT department while, because before "migration" or "acquisition" they where no troubles at all..... This script is just for MS Word files as template usage in Excel or Powerpoint is less common. So how are we going to resolve this issue? Exactly, with a Powershell script that removes any existing template and default behaviour of Word is that Main.dot or Normal.dot will fill that gap.


Requirements to solve this issue:
- Make sure no other template path are used in the directories you want to run this script in.
   ( This script removes every template path, inclusing one's that are correct )
- Microsoft Word 2007 or 2010 installed on the location you are running the powershell script from.
  The script uses Word objects to open and save the (remote) files.
- Microsoft Powershell in Administrator Mode ( evaluated permissions )
- A (temporary) drive letter (net use) towards the top of the tree where you want to start the script.



The Powershell script, removing all template from within Word documents:
########################################################################
## Created by: Ben Oostdam  / copyright (c) 2011
## Feel free to use this script for your own benefit.
## Never remove this copyright and version history.
## Additional comments or improvement suggestions can be mailed to
Dit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken.
## Usefull suggestions will be added and your name will be added in the version list as well.
## =====================================================================
## Title          : FixDocTemplates.ps1
##
## Description : Removes any Word template location from a Word file and saves it back.
##
## Author       : Ben Oostdam with assistance and idea's from RV and BS.
##
## Date          : 12/16/2011
##
## Input         : Driveletter or UNC-path as parameter
##                                    
## Output        : Default on screen, use Output-File or Export-CSV through commandline for
##                     reporting reasons afterwards. ( Remember, to remove .FullName from Write Host
##   
## Remarks     : Remove the "Write Host" text on success if you don't want to be informed
##                    about the files modified. Etc. etc...
##              
## Notes       : Sign this script, or add a Set-Execution Statement manually before executing.
##                    Replace the null in $doc.set_AttachedTemplate to set a custom template.
##
## Tags        : Word, doc, docx, rtf, template, location, powershell
##
## Versions    : v.1.8 Added personal comment mail address and description
##                   v.1.7 Tested usage without FullName but did not succedeed
##                   v.1.6 Added the original timestamps
##                   v.1.5 Added search structure below, by using ChildItem
##                   v.1.4 Added the Opening Error skip
##                   v.1.3 Added the Openfile test
##                   v.1.2 Added the write test
##                   v.1.1 Improved Word Application Objects
##                   v.1.0 Initial setup
##
## ====================================================================

function Test-IsWritable(){
  [CmdletBinding()]
  param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][psobject]$path)

  process{
    Write-Verbose "Test if file $path is writeable"
    if (Test-Path -Path $path -PathType Leaf){
      $target = Get-Item $path -Force
      try{
        $writestream = $target.Openwrite()
        $writestream.Close() | Out-Null
        Remove-Variable -Name writestream
        Write-Output $true
      }
      catch{
        Write-Output $false
      }
      Remove-Variable -Name target
    } else {
      Write-Output $false
    }
  }
}

if ($args.Count -le 1){
  if ($args -ne $null){
    $folder = $args[0]
  } else {
    $folder = Split-Path $MyInvocation.MyCommand.Path
  }
 
  $b = Get-ChildItem -Include *.doc,*.docx -Recurse -Path $folder

  foreach ($i in $b) {
    If (Test-IsWritable $i.FullName) {

      # Get original timestamps
      $ct = $i.CreationTime
      $lw = $i.LastWriteTime
      $la = $i.LastAccessTime

      $word = new-object -comobject "Word.Application"
      $word.Visible = $false
#      $word.DisplayAlerts = "wdAlertsNone"
#      $word.WordBasic.DisableAutoMacros
#      $word.AutomationSecurity = "msoAutomationSecurityLow"
#      $word.AutomationSecurity = "msoAutomationSecurityForceDisable
"

      try {
        $doc = $word.Documents.Open($i.FullName)

        if ($doc -ne $null){
          # Remove template
          $doc.set_AttachedTemplate([ref]$null)

          $doc.saveas([ref]$i.FullName)
          $doc.close([ref]$false)
          Write-Host "Processed: $i.FullName, success."
        } else {
          Write-Host "Skipped:   $i.FullName, unable to open file."
        }
      }
      catch {
        Write-Host "Skipped:   $i.FullName, unexpected error processing file."
      } 

      $word.quit()

      # Set the Original timestamps back
      $i.CreationTime = $ct
      $i.LastWriteTime = $lw
      $i.LastAccessTime = $la
    } else {
      Write-Host "Skipped:   $i.FullName, file is in use."
    }
  }
} else {
  Write-Host "Error:     too many parameters."
}

##  End of the Script
----------------------------------------------------------------------------------------------------------------------------------------

You can download the latest version of this script from this link.


Hope this will help you solving your (bulk) Word-issues. It solved my problems over several thousand of files!! Remember to isolate files, espescially if you are using your own templates in Word files, but this script helped me a lot during migrations and "data" from other companies.  Again, if you have any comments or suggestions to improve this script,.. mail me at the address that is mentioned at the top of the script. Lets improve our working-lives and share so the world can benefit from it.


Some extra's, notes and comments:
- This script saves the document back with the original timestamp, which is an additional benefit for the end-users.
- Depending on the number of files the script has to go through, running this, can take a long time, be aware of this!
- Incidentally,.. I've seen some strange behaviour of un-correct saving the Word-file back to disc. Mainly on using UNC-paths. 
  This results in an "open" Word session in your taskbar, per open file. You can close that, but not recover the file name.
  Please use a drive letter, and check during running the open Word session in order to prevent other issue's. 


I probably do not have to remind you, that you should always backup your data before you change it.
Therefore this posting is "as is" without express or implied warranty. But I guess you knew that already....

 

-----------------------------------------------------------------------------------------------------

Ben OostdamBen Oostdam has been working with Windows systems since 1993. Worked for several companies as a system administrator, and is currently a Senior Engineer for Qurius Professional Services Infrastructure in the Netherlands.

Disclaimer: The information contained in this website/article is for general information purposes only. The information is provided as is, by Ben Oostdam and while we endeavour to keep the information up to date and correct, we make no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the website or the information, products, services, or related graphics contained on the website for any purpose. Any reliance you place on such information is therefore strictly at your own risk. In no event will we be liable for any loss or damage including without limitation, indirect or consequential loss or damage, or any loss or damage whatsoever arising from loss of data or profits arising out of, or in connection with, the use of this website. Through this website you are sometimes able to link to other websites which are not under my control. I have no control over the nature, content and availability of those sites. The inclusion of any links does not necessarily imply a recommendation or endorse the views expressed within them. Every effort is made to keep the website up and running smoothly. However, I take no responsibility for, and will not be liable for, the website being temporarily unavailable due to technical issues beyond our control. All entries in these articles, are my individual opinion, or from co-writers and they don't necessary reflect the opinion of my employer.



 

Thursday the 19th, September 2019. All rights reserved.. // Oostdam WebDesign