Wednesday, 26 March 2014

Powershell - Creating a scheduled task to run a script gathering application logs from a number of servers

Hmmm.... long title for such a small task.

As the title says - gathering the application log from a number of servers, running it as a scheduled task.

First of lets start with the script

## List of servers
$server = @('Server1','Server2','Server3');
## Get the application log of every server listed above
foreach ($computer in $server) {
Get-EventLog -ComputerName $server -LogName "Application" |
Export-csv -Path "C:\Data\Log_$((Get-Date).ToString('yyyy-MM-dd-hhmmss')).csv"}

I have found that the script does keep running and running and running......
(Note to self - fix!)

Which leads me onto the scheduled task.

The task is going to run on Windows 2008 R2 server.
Administrative Tools > Task Scheduler > Task Scheduler Library.

General
Created a Domain account purely for this scheduled task.
Run whether user is logged on or not.

Triggers
On a schedule
Daily
Set date/time
Set occurance
Stop task if runs longer than (I set mine to 4 hours)
Check the enabled box

Actions
Action - Start a Program
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments: & 'C:\<path>\script-name.ps1'

Conditions
Left at default

Settings
Leave at default settings
History
Log of the task

The scheduled task should now run - the difficult part was working out what arguments should be added to the Actions.