Running Powershell script as scheduled task
Asked Answered
A

5

0

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
Alienate answered 31/1, 2013 at 22:3 Comment(2)
My first guess would be that it's some privilege matter. What user do you use to run the scheduled task? Does that user have the privileges to read and write the files?Tholos
Try scheduling some test.ps1 with "hello" | out-file .\test.txt and check out this Scripting Guys post and this serverfault threadSudd
A
3

Figured it out. I didn't even think to set the execution policy in both the 32 and 64 versions of powershell. When running it manually, it was using one, and running it through scheduled tasks was using the other. Once I made sure it was set it both, everything is good to go. Thank you all for your responses.

Alienate answered 1/2, 2013 at 20:13 Comment(0)
M
2

Keep your script as it is, and try the following from the Powershell command line.

$Schedule = "schtasks /CREATE /TN 'Word Doc' /SC WEEKLY /RL HIGHEST /TR powershell 'C:\temp\Script1.ps1' /F"
$Start = "schtasks /RUN /TN 'Word Doc'"
$Schedule = [ScriptBlock]::Create($Schedule)
$Start = [ScriptBlock]::Create($Start)
Invoke-Command -ScriptBlock $Schedule
Invoke-Command -ScriptBlock $Start

This will create a weekely task, and the final line will execute the scheduled task immediately so you can test if it works. If it does then you can modify the $Schedule to match the start times that you require.

I couldn't find a way to run the task with two separate dates from the schtasks command line but I have found a work around as follows:

1) Create the following XML which has the time definitions inside it:

    <?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2013-02-01T00:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
    <CalendarTrigger>
      <StartBoundary>2013-02-01T05:30:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Actions Context="Author">
    <Exec>
      <Command>powershell</Command>
      <Arguments>C:\temp\Script1.ps1</Arguments>
    </Exec>
  </Actions>
</Task>

2) Set the $Schedule variable as follows:

$Schedule = "schtasks /CREATE /XML 'C:\temp\Word Doc.xml' /TN 'Word Doc'"

Make sure you change the values where required to reflect the correct file names.

Mongol answered 1/2, 2013 at 10:20 Comment(2)
How would I rewrite the schedule line if I wanted to do this twice daily, once at midnight and once at 5 am?Alienate
I'll post another answer as the I don't have enough space here.Mongol
I
1

Are you sure you script not just failing because your running out of shell memory? You can increase it with:

 Set-item wsman:localhost\Shell\MaxMemoryPerShellMB 512

We've had issues with scripts having such issues such as yours so its always worth a try.

Iquitos answered 1/2, 2013 at 10:26 Comment(2)
Tried it, no luck. Would the script work when run through ps manually if this were the issue?Alienate
well it was a long shot really.Iquitos
G
0

Please commented every line with Write-Host and try to run this powershell with schedule task. Write-Host error out when you with schedule task manager.

    $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
Gibert answered 1/2, 2013 at 3:19 Comment(0)
D
0

It sounds like you want to see the progress of the script as it runs, but if that is not important you can try creating a .vbs script and running that instead.

command = "powershell.exe -command C:\test\C:\temp\Script1.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0
Set WinScriptHost = Nothing
Daynadays answered 1/2, 2013 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.