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.
Microsoft Windows Task Scheduler can run PowerShell scripts, but to do so you will first need to specify it as an argument to PowerShell. Hopefully this article will help you automate many of your daily activities on your Windows system.
To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.
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.)
The function needs to be imported first. I would recommend saving the function as a module and placing it in the modules folder in either system32 or program files. This way, when powershell is launched, it will automatically import your function.
After you do that, the task scheduler is very simple.
Program/Script
Powershell
Add arguments(optional):
-Command &{ServiceRestart -ErrorLog 'ServerName\C$\Users*****\Documents\log\ScriptErrors.txt' -Services 'foo1','foo2' -MaxSize '5MB'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With