Powershell run 5 batch files, create a log file, and verify folder location

Recently was asked to run a series of batch files.
Below is a PowerShell script that will run five batch files, create a log file for each execution, and verify the folder location before running the batch files.
# Define the folder location and batch files
$folderPath = "C:\Path\To\Your\BatchFiles"
$batchFiles = @("batch1.bat", "batch2.bat", "batch3.bat", "batch4.bat", "batch5.bat")
$logFolder = "C:\Path\To\Your\Logs"
# Verify if the folder exists
if (-Not (Test-Path -Path $folderPath)) {
Write-Output "The folder path $folderPath does not exist."
exit
}
# Create log folder if it doesn't exist
if (-Not (Test-Path -Path $logFolder)) {
New-Item -ItemType Directory -Path $logFolder
}
# Run each batch file and create a log file
foreach ($batchFile in $batchFiles) {
$batchFilePath = Join-Path -Path $folderPath -ChildPath $batchFile
$logFilePath = Join-Path -Path $logFolder -ChildPath "$($batchFile).log"
if (Test-Path -Path $batchFilePath) {
& $batchFilePath *>&1 | Tee-Object -FilePath $logFilePath
Write-Output "Executed $batchFile and logged output to $logFilePath"
} else {
Write-Output "Batch file $batchFilePath does not exist."
}
}
Explanation:
- Define Paths: The script sets the folder path where the batch files are located and the log folder path.
- Verify Folder: It checks if the folder containing the batch files exists. If not, it exits the script.
- Create Log Folder: If the log folder does not exist, it creates it.
- Run Batch Files: It iterates through each batch file, verifies its existence, runs it, and logs the output to a corresponding log file.
This script ensures that each batch file’s output is captured in a log file, and it verifies the necessary folder locations before proceeding. If you need any adjustments or further customization, feel free to let me know!