Command Line

Batch File to Run PowerShell Scripts and Log Console Output to Log Files

The easiest way to schedule a PowerShell script is to run it from a DOS batch file, and schedule the execution of the batch file on a Windows server via the Task Scheduler. The following batch file will run a PowerShell script, and also organise output from the PowerShell (via Write-Host) into a text file, stored in a sensibly formatted sub-folder and filename structure.


REM create a logfile name (log_yyyy-mm-dd-hh-mm-ss.log)
SET logfilename=log_%DATE:~-4%-%DATE:~3,2%-%DATE:~7,2%-%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%.log

REM create a folder name (log_yyyy-mm-dd)
SET foldername=log_%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2%

REM create a log subdirectory
mkdir c:\logs\%foldername%

REM run the powershell script and pipe output to the logfile
powershell.exe "c:\scripts\MyScript.ps1" > "c:\logs\%foldername%\%logfilename%"

The take-away from this script is almost certainly the arcane DOS batch file comments required to get bits and pieces of the date and time.

Posted by Jonathan Beckett in Notes, 0 comments