Search code examples
powershellvbscriptscheduled-tasksdynamics-ax-2012

Get-Service in .vbs file and Task Scheduler


I'm completely new at VBS scripts, however I prepared one to monitor Dynamics AOS service.

while ((Get-Service -name "AOS60*").status -eq "Running")
{Start-Sleep -s 30}
Send-MailMessage -From AOSmonitor@abc.com -To hub.pia@abc.com -Body "AOS    Stopped" -Subject "AOS3 stopped" -SmtpServer 89.216.216.116

It works fine when I paste it into PowerShell and I get an email, but when I save it into file aos.vbs and try to run it.

PS C:\> cscript aosMon.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

C:\aosMon.vbs(1, 9) Microsoft VBScript compilation error: Syntax error

Any idea what I do wrong?

Similar way when I try to run this script in Task Scheduler (basic task, one time) it stays in Running and no email sent.

enter image description here


Solution

  • The PowerShell file extension is .ps1 and should be saved with the encoding UTF8-bom. vbs is short for visual basic script, which is not in any way synonymous with PowerShell. You should be able to save your contents into a filename.ps1 file and run it from the scheduler directly.

    filename.ps1

    do {
        Start-Sleep -Seconds 30
    } while ((Get-Service -Name 'AOS60*').Status -eq 'Running')
    
    $mailArgs = @{
        From       = 'AOSmonitor@abc.com'
        To         = 'hub.pia@abc.com'
        Subject    = 'AOS3 stopped'
        Body       = 'AOS Stopped'
        SmtpServer = '89.216.216.116'
    }
    Send-MailMessage @mailArgs
    

    From here, you can set up the scheduled task. In Action:

    Program/script:

    %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe
    

    Add arguments (optional):

    -NoProfile -NonInteractive -File "PATH\TO\filename.ps1"
    

    Footnote: if you run into issue with execution policies, you can add

    -ExecutionPolicy Bypass
    

    to the arguments (before -File) to get around that.