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

Just another Tech site

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

Below is a PowerShell script that will run five batch files, create a log file, and verify if a folder exists. If the folder does not exist, it will create the folder.

# Define the folder path and log file path
$folderPath = "C:\YourFolderPath"
$logFilePath = "C:\YourFolderPath\log.txt"

# Verify if the folder exists, if not, create it
if (-Not (Test-Path -Path $folderPath)) {
    New-Item -ItemType Directory -Path $folderPath
    Add-Content -Path $logFilePath -Value "[$(Get-Date)] Folder created: $folderPath"
} else {
    Add-Content -Path $logFilePath -Value "[$(Get-Date)] Folder already exists: $folderPath"
}

# Define the batch files to run
$batchFiles = @(
    "C:\PathToBatchFile1.bat",
    "C:\PathToBatchFile2.bat",
    "C:\PathToBatchFile3.bat",
    "C:\PathToBatchFile4.bat",
    "C:\PathToBatchFile5.bat"
)

# Run each batch file and log the result
foreach ($batchFile in $batchFiles) {
    if (Test-Path -Path $batchFile) {
        & $batchFile | Out-File -Append -FilePath $logFilePath
        Add-Content -Path $logFilePath -Value "[$(Get-Date)] Successfully ran: $batchFile"
    } else {
        Add-Content -Path $logFilePath -Value "[$(Get-Date)] Batch file not found: $batchFile"
    }
}

Explanation:

  1. Folder Verification and Creation:
    • The script checks if the specified folder exists using Test-Path.
    • If the folder does not exist, it creates the folder using New-Item and logs this action.
    • If the folder already exists, it logs that the folder was already present.
  2. Batch File Execution:
    • The script defines an array of batch file paths.
    • It iterates over each batch file path, checks if the file exists, and then executes it.
    • The output of each batch file execution is appended to the log file.
    • It logs whether each batch file was successfully run or not found.

This script should be run with appropriate permissions to ensure it can create folders and execute batch files. If you have any specific requirements or need further customization, feel free to let me know!