I am using the powershell
script below to open several word documents, update the form fields in them, and then close them. First, I'll note that if this script is run from the command line or by right clicking the file and selecting Run with Powershell
basically doing it manually in any way, it will execute just fine. However, if I try to run this as a scheduled task, one of two things happen.
I have tried several different forms of syntax for this, but all produce one of the same two results. Either A) The script says it started and finishes in about 3 seconds without doing anything, or B) The script starts, I can see Word open in task manager, but there is no command window showing the progress like there is normally and Word just gets hung up after about 2 minutes. Really the only syntax that got me to option B there is putting powershell
as the action, .\Script1.ps1 as the argument, and the folder as the start in location. I tried a few slight variations of this syntax, such as using the full path of powershell
, etc. When I end Word in task manager when it hangs, the scheduled task says that it completed successfully. Anyone have any ideas? The script is as follows:
$filearray = 1..12
$filename="E:\Form0801"
$word=new-object -com Word.Application
$word.Visible=$False #Making this true
#does not show word if run from scheduled task
Write-Host "DO NOT CLOSE THIS WINDOW!"
try
{
foreach ($i in $filearray)
{
if($i -lt 10){$filename="E:\Form080" + $i + ".dot"}
else{$filename="E:\Form08" + $i + ".dot"}
$doc=$word.Documents.Open($filename)
$word.ActiveDocument.Fields.Update()
$doc.SaveAs([REF]$filename)
$doc.Close()
Write-Host "File " $filename " has been updated successfully"
}
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
"A problem occurred while opening one of the files."
$error[0]
}
$word.Quit()
# End Word Application