Run .bat File From PowerShell .ps1 Script

PowerShell scripts can run any Windows command or .bat file. This page shows one of the several ways to run Windows command lines from PowerShell.

Example: Run a .bat file from a PowerShell script with cmd.exe

Run this .bat file from a PowerShell script.
See also Logging Jobs with Start-Transcript

.bat File for this example: C:\Demo\hello_world.bat

echo "Hello World" rem When editing save as "ASCII", not "UTF"

PowerShell .ps1 Script: Run_BAT_file.ps1

######### Start Logging ######################################### $DateTimeStr = Get-Date -UFormat %Y-%m-%d@%H-%M # date-time string for log file name [string]$RunLogsPath = "$($PSScriptRoot)\Run_Logs" # path for log file created below [string]$Transcript_FileRef = "$($RunLogsPath)\RunLog_$DateTimeStr.txt" Start-Transcript -Path $Transcript_FileRef -Append -Verbose #### Start DOS .bat file with cmd.exe (command interpreter) $BatFileName = "C:\Demo\hello_world.bat" Write-Host "--------------------------------------------------------" Write-Host "Running DOS .bat file = $BatFileName" cmd.exe /c $BatFileName Stop-Transcript # optional
Notes:

Line 3 - Uses the path of the .ps1 script as the path to the \Run_Logs folder.

Line 5 - Creates a log file in C:\Demo\Run_Logs and begins to send log records to it.
Makes the folder \Run_Logs if the folder doesn't exist.

Line 8 - Assigns the path & file name of the .bat file to run.

Line 12 - Runs the .bat file with cmd.exe.

  • Alternative: cmd.exe /c "C:\Demo\hello_world.bat"

 

Log File Created in C:\Demo\Run_Logs

Example: Log file created C:\Demo\Run_Logs\RunLog_2022-02-14@19-26.txt

********************** Windows PowerShell transcript start Start time: 20220214192617 Username: G3\msliv RunAs User: G3\msliv Configuration Name: Machine: G3 (Microsoft Windows NT 10.0.19044.0) Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe Process ID: 15112 PSVersion: 5.1.19041.1320 PSEdition: Desktop PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.19041.1320 BuildVersion: 10.0.19041.1320 CLRVersion: 4.0.30319.42000 WSManStackVersion: 3.0 PSRemotingProtocolVersion: 2.3 SerializationVersion: 1.1.0.1 ********************** Transcript started, output file is C:\Demo\Run_Logs\RunLog_2022-02-14@19-26.txt -------------------------------------------------------- Running DOS .bat file = C:\Demo\hello_world.bat C:\WINDOWS\system32>echo "Hello World" "Hello World" C:\WINDOWS\system32>rem When editing save as "ASCII", not "UTF" ********************** Windows PowerShell transcript end End time: 20220214192617 **********************

Links to docs.microsoft.com

Related Pages