Powershell – Pass Powershell parameters within Task Scheduler

powershellscheduled-tasks

function ServiceRestart
{
    Param
    (
        $ErrorLog,
        $Services,
        $MaxSize    
    )

    $Time = Get-Date -Format 'yyyy:MM:dd HH:mm:ss'
    $Result = (Get-Item $ErrorLog).length 


    if($Result -gt $MaxSize)
    {
        Clear-Content $ErrorLog
    }

    Try 
    {
        Foreach($Service in $Services)
        {
            Restart-Service -DisplayName $Service -ErrorAction Stop
        }
    } Catch 
      {
        "ERROR: $Service could not be restarted $Time" | Add-Content $ErrorLog 
      }
}

ServiceRestart -ErrorLog -Services -MaxSize

I need to pass in the following parameters from Task Scheduler
– Errorlog
– Services
– MaxSize

I currently have my Task Scheduler setup like this
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments(optional):
-Command "& \ServerName\C$\Users*****\Documents\Scripts\Scheduled-ServiceRestart.ps1
-ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt'
-Services 'foo1' , 'foo2'
-MaxSize '5MB'"

When I run the scheduled task nothing happens, what could be going wrong.

Best Answer

I recommend scheduling the task to use the -File parameter rather than -Command. Example:

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments (optional): -NoProfile -ExecutionPolicy Bypass -File "Scheduled-ServiceRestart.ps1" -ErrorLog "ScriptErrors.txt" -Services "foo1","foo2" -MaxSize 5MB

Start in (optional): C:\Users\<username>\Documents\Scripts

You can specify the starting directory for the script in the "Start in" property for the task and avoid the lengthy path names to the script and log files. (Note that I am assuming you are running a copy of the script on the local computer, not over the network, which adds potential complications and possibilities for failure.)