How to Run a Batch File from a PowerShell Script?

powershell run batch file

Batch files provide a handy way to bundle together commands, automate tasks, and execute scripts in Windows. But did you know, you can also call batch files directly from PowerShell scripts? Batch files are simple scripts that can automate a series of tasks, and when combined with PowerShell, they become a powerful tool. In this step-by-step guide, we’ll explore the ins and outs of running batch files and CMD commands from within PowerShell. We will begin by understanding what a batch file is and how it works. We will then move on to the benefits of running bat files from PowerShell and the different PowerShell commands that can be used for this purpose. You’ll learn various methods to launch batch scripts, pass arguments, assign outputs, and automate batch operations completely from PowerShell.

Whether you want to migrate legacy batch scripts over to PowerShell or combine the two for next-level automation, this guide has you covered. Follow along as we unlock the full potential of PowerShell and batch scripts together!

What is a batch file, and how it works?

Before we begin, let’s first understand what a batch file is. A batch file is a simple script that contains a series of commands or scripts that are executed in sequence in the Windows operating system. These commands can be used to perform a wide range of tasks, including file operations, folder operations, system operations, and more. It is usually saved with a .bat or .cmd extension and can be executed by double-clicking on the file. Batch files are used to automate repetitive tasks, and they are commonly used in Windows environments on local or remote machines. By calling batch scripts and commands within PowerShell, you open up whole new possibilities for advanced automation and workflow orchestration.

The syntax of a batch file is simple. Each command is written on a separate line, and comments can be added using the REM keyword. Bat files can also use variables, which can be set using the SET keyword. These variables can then be used in the batch file to store and retrieve values.

Benefits of running batch files from PowerShell

Running batch files from PowerShell provides several benefits. First, it enables us to use the powerful scripting capabilities of PowerShell to automate our tasks. PowerShell provides a rich set of commands and functions that can be used to manipulate files, folders, and system settings. By using PowerShell to run batch files, we can combine these commands and functions with the commands in our batch file to create powerful scripts.

Second, running batch files from PowerShell provides better control and error handling. PowerShell provides a robust error-handling mechanism that enables us to handle errors gracefully. We can use the Try-Catch-Finally construct to catch and handle errors that occur during the execution of our bat file.

Finally, by calling batch files from PowerShell, we can take advantage of the security features provided by PowerShell. PowerShell provides several security features, including execution policies, that can be used to control the execution of scripts and prevent malicious scripts from running on our system.

Why Run Batch Files from PowerShell?

There are a few great reasons to execute batch files from PowerShell rather than standalone:

  • Automate complex workflows by combining batch and PowerShell
  • Migrate existing batch scripts over to PowerShell
  • Avoid switching contexts to run batch operations
  • Encapsulate and reuse batch operations in script modules

PowerShell offers advanced functionalities that are not present in batch files. So, why not get the best of both worlds? By invoking batch files directly from PowerShell, you get full control and scriptability without needing to manually execute batch jobs separately.

How to run a batch file from PowerShell?

Running a batch file from PowerShell scripts is a simple process. PowerShell provides several commands that can be used to run batch files inside the PowerShell environment. Let’s take a look at some of the most commonly used commands:

Method 1: Start-Process cmdlet

We can use the Start-Process cmdlet to execute a batch file. The syntax of the Start-Process cmdlet is as follows:

Start-Process -FilePath <path-to-batch-file> -ArgumentList <arguments> -Wait

The -FilePath parameter specifies the path to the batch file, while the -ArgumentList parameter specifies any arguments that need to be passed to the batch file as an array of strings. The -Wait parameter specifies that PowerShell should wait for the batch file to complete before continuing. Please note, that if your PowerShell session isn’t already elevated, this will trigger a UAC prompt.

Example: Executing a Bat File from a PowerShell Script

Let’s start with a simple example. Say we have a batch file called Backup-Database.bat that we want to run from PowerShell.

@echo off
echo Starting backup process...

xcopy C:\Backup\Live D:\Archive\Live /E /I
if %ERRORLEVEL% NEQ 0 (
  echo Backup failed with error level %ERRORLEVEL%
) else (
  echo Backup completed successfully.
)

echo Process finished.

We can call it using the Start-Process cmdlet:

Start-Process -FilePath "C:\Temp\Backup-Database.bat" -Wait

This will execute the bat file in a separate command prompt window and wait for it to complete before continuing.

How to Run a Batch File from PowerShell

Batch file with Space in Name

Running batch files from PowerShell scripts is easy. To execute a batch file from a PowerShell script, just add the file path to the batch file within the PowerShell script. For example, to run a batch file called “Deploy App.bat” you would add the following line. If your batch file name contains spaces, surround it with double quotes:

Start-Process -FilePath "C:\Scripts\Deploy App.bat" -Wait -NoNewWindow

This passes the full batch file path to cmd.exe as a single argument. The “NoNewWindow” parameter instructs PowerShell to execute the bat file in the current window without opening another window. For more information on the Start-Process cmdlet, refer: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.2

Method 2: The & Operator

The & operator (AKA: Call Operator) runs a command like a PowerShell function. We can use the & operator to execute a batch file. The syntax is as follows:

& <path-to-batch-file>

Here is an example of how to use the & operator to execute a batch file:

& "C:\Scripts\deploy-app.bat"

#Also works (when the batch file is located relative path or drive letter) & .\deploy-app.bat 

Method 3: Invoke-Item cmdlet

The Invoke-Item cmdlet opens a file or folder in its associated application. We can use the Invoke-Item cmdlet to execute a batch file. The syntax is as follows:

Invoke-Item <path-to-batch-file>

This allows you to run and execute the batch file from the PowerShell script. Here is an example of how to use the Invoke-Item cmdlet to execute a batch file from the PS script:

Invoke-Item "C:\Scripts\deploy-app.bat"

You can also use the Invome-command cmdlet:

Invoke-Command -ScriptBlock { C:\Scripts\deploy-app.bat }

Method 4: Running Batch Files with CMD.exe

Another approach is to invoke the cmd Window and pass in the batch file to execute. Running a batch file using cmd.exe from within a PowerShell environment is relatively straightforward. Below are some examples to show how to do this:

cmd.exe /c C:\Scripts\deploy-app.bat

You can also execute conditional logic within the batch commands:

cmd.exe /c "echo 'Is it raining? (yes/no)' && set /p answer= && if '%answer%'=='yes' (echo 'Take an umbrella!') else (echo 'Enjoy the weather!')"

All these methods work with any other hosts like PowerShell ISE, Visual Studio Code, etc.

Call Bat File from the PowerShell console

Let’s see the steps of running a batch file in PowerShell.

  1. Step 1: Open PowerShell: To begin, open PowerShell on your Windows computer. You can do this by searching for “PowerShell” in the Start menu or by pressing the Windows key and typing “PowerShell” into the search bar.
  2. Step 2: Navigate to the Directory Containing the Batch File: Once PowerShell is open, you need to navigate to the directory that contains the batch file you want to run. To do this, use the “cd” command followed by the path to the directory. For example, if your batch file is located in the “Documents” folder, you would enter “cd C:\Scripts”.
  3. Step 3: Run the Batch File: After navigating to the correct directory, run the batch file by typing the name of the file followed by “.bat”. For example, if your batch file is named “Deploy-App.bat”, you would enter “Deploy-App.bat” in PowerShell and press Enter.
  4. Step 4: Check for Errors: Once you’ve run the batch file, check PowerShell for any errors. If there are no errors, the batch file should have executed successfully.
run batch file in powershell

Running batch files with parameters

Batch files can accept arguments, which can be passed to them at runtime. We can also pass arguments to a batch file when running it from PowerShell. To pass arguments to a batch file, we need to use the -ArgumentList parameter with the Start-Process cmdlet. The syntax is as follows:

Start-Process -FilePath <path-to-batch-file> -ArgumentList <arguments>

You can access the arguments using tokens %1, %2, etc. inside your batch script. E.g.

@echo off
IF "%1"=="install" (
    echo Installing the program...
    REM Install the application
    echo Done!
)
IF "%2"=="silent" (
    echo Using Silent mode...
    echo Done!
)
echo App Deployment has been complete!
Pause

The echo command in the bat file is equivalent to Write-Output in PowerShell. Here is an example of how to pass arguments to a batch file:

Start-Process -FilePath 'C:\Scripts\deploy-app.bat' -ArgumentList "install", "silent"

In this example, we are passing two arguments to the batch file.

Assigning Batch File Output

Capturing the output of a batch file when running it from PowerShell can be very useful for logging, debugging, or for further data processing. To capture output from the batch file, store the result Start-Process in a variable:

Start-Process -FilePath 'C:\Scripts\deploy-app.bat' -RedirectStandardOutput 'C:\Temp\Output.txt' -Wait -WindowStyle Hidden

This provides an easy way to get batch output directly within PowerShell.

Redirecting output to a file

We can redirect the output of a batch file to a file using the > operator. This operator redirects the output to a file instead of the console. Here is an example:

& "C:\Scripts\deploy-app.bat" > "C:\Scripts\output.txt"

In this example, the output of the batch file is redirected to a file called “output.txt”.

Using cmd.exe to capture the output

You can also use cmd.exe to capture the output. The /c flag tells CMD.exe to run the command that follows it:

$Output = cmd.exe /c C:\Scripts\deploy-app.bat | Out-String

This runs deploy-app.bat via cmd.exe and passes the stdout to Out-String to convert it to a string in PowerShell.

Running Inline Batch Commands in PowerShell

You can execute one-off batch commands directly from PowerShell:

$output = cmd /c "ping localhost -n 3"

This pings localhost 3 times and captures the output. So you don’t need an actual .bat file – you can run inline batch code snippets too.

Invoke-Expression "cmd.exe /c 'dir C:\Backup'"

Output of the above example:

run batch command from powershell

Calling Batch Files within PowerShell Functions

Once you’ve tested batch execution from PowerShell, consider encapsulating it in a reusable PowerShell function.

Function Invoke-DevBatchScript {
   $output = Start-Process -FilePath 'C:\Scripts\deploy-app.bat' -RedirectStandardOutput 'C:\Temp\Output.txt'
   Write-Output $output.StandardOutput
}

Invoke-DevBatchScript

Now you can call Invoke-DevBatchScript from any PowerShell script to run your batch operation. This makes it easy to integrate batch workflows into PowerShell’s modular approach.

Run Batch File as Administrator in PowerShell

If your bat file requires administrator privileges, You can use the “-Verb RunAs” switch in the Start-Process cmdlet:

Start-Process -FilePath "C:\Scripts\deploy-app.bat" -Verb RunAs

How to Run a PowerShell Script from a Batch File?

In some scenarios, you may need to run a PowerShell script file from a batch file. You can call a PowerShell script using the “PowerShell -command ‘PowerShell commands'” syntax within a batch file.

Creating a batch file to run a PowerShell script

Creating a batch file to run a PowerShell script is a straightforward process. Follow these instructions to get started:

  1. Open any PowerShell-compatible editor of your choice, such as Notepad, PowerShell ISE, or Visual Studio.
  2. To call the PowerShell script, type the following command into the text editor: powershell -File “path/to/your/script.ps1”. Replace “path/to/your/script.ps1” with the actual path to your PowerShell script. Make sure to include the correct file extension (.ps1).
  3. Save the file with a .bat extension, such as “RunScript.bat”. Choose a location that is easily accessible.
batch file to execute powershell script

That’s all! You have now created a batch file that can run your PowerShell script without user intervention. To run the bat file, you can simply double-click on the batch file from File Explorer, and it will automatically call the PowerShell script (Notice the difference? The default action for PowerShell files .ps1 is opening the file in editors like notepad, but the .bat file directly executes the script!). Or run it from the Command Prompt or PowerShell as well.

Run PowerShell Script from Batch File

The following line of code sends the output of a PowerShell command to a text file.

powershell.exe -Command "Get-Service | Out-File 'C:\Scripts\Services.txt'"

Alternatively, You can call the PowerShell file from the batch file as:

powershell.exe -File -noexit "C:\Scripts\BackupScript.ps1"

To see the PowerShell output, you can add the -noexit parameter. This keeps the PowerShell window open after running the script so you can see any output.

You can also start a new PowerShell session from your batch file like this:

PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -File "C:\Scripts\deploy-app.bat"' -Wait}" 

This will open a new PowerShell window, run the script inside PowerShell, and close the window at the end of the script.

Run the PowerShell Script as Administrator from the Batch File

To run a PowerShell script with administrative rights from a batch file, use the -Verb RunAs parameter as shown below:

powershell.exe -Command "Start-Process 'C:\Scripts\Backup.ps1' -Verb RunAs"

The above code is equivalent to “Run as Administrator” in Windows GUI. Let’s make it a bit more detailed:

PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "C:\PathToScript.ps1 %arg1% %arg2%"' -Verb RunAs -Wait}" 

Pass Arguments and Variables from Batch File to PowerShell

You can also pass arguments and variables from the batch file to the PowerShell script. For example, Here is the bat file that calls a PowerShell PS1 file:

powershell.exe -File "C:\Temp\Helloworld.ps1" -Name "John"

Then, in your PS1 script, access it like:

Param(
    [string]$Name
)

Write-Output "Hello $Name"

This allows the batch file to dynamically pass data to the script.

Troubleshooting common issues when running batch files from PowerShell

Running batch files from PowerShell is generally straightforward, but like any technical task, it can sometimes result in unexpected behavior or errors. Below are some common issues you might encounter when running batch files from PowerShell, along with troubleshooting steps to resolve them.

Syntax Errors

The command interpreter executes batch files, which is a different program from PowerShell. Thus, we must write the commands in our batch file using the correct syntax for the command interpreter. We can run our batch file from the command prompt to verify its correctness.

File Not Found or Path Errors

PowerShell may throw an error message like “The system cannot find the file specified”. Possible Solutions: Double-check the file path. Ensure you’ve either navigated to the folder containing the batch file or provided the full path to the file. Check for typos in the file name or path.

Permission Issues

When running batch files from PowerShell, we may encounter permission issues if the batch file requires elevated privileges. Run PowerShell as an administrator. To run a batch file with admin privileges, we can use the Start-Process cmdlet with the -Verb RunAs parameter. The syntax is as follows:

Start-Process -FilePath <path-to-batch-file> -Verb RunAs

Make sure that the batch file and the PowerShell script are both run with administrative permissions.

Batch File Runs, but Nothing Happens

Sometimes, The batch file seems to run but doesn’t produce the expected output. You can redirect the output of the batch file to a text file to debug.

Execution Policy Restrictions

The execution policy may block the execution of PowerShell scripts. To fix, change the script execution policy using Set-ExecutionPolicy, but do this carefully and understand the implications.

Best practices for running batch files from PowerShell

When running batch files from PowerShell, there are several best practices that we should follow:

Use absolute paths

We should always use absolute paths when referencing files or folders in our batch files. This ensures that the batch file can be executed from any directory. Leverage -ArgumentList to pass arguments to the batch script. Using the relative path might execute the wrong file if you don’t set the current working directory as expected.

Use error handling

We should use error handling to handle errors gracefully. This helps us to identify and resolve issues quickly. Capture output with -PassThru or redirect via | Out-String. Escape special characters like | > with ^ if needed

Use comments

We should add comments in our batch files to explain what each command does. This makes it easier to understand and modify the batch file in the future.

Conclusion

Running batch files from PowerShell is a powerful way to automate tasks in Windows. By using PowerShell to run batch files, we can leverage the power of both tools to create powerful scripts. In this guide, we have explored the process of running bat files from PowerShell. We have discussed the benefits of running batch files from PowerShell, the different PowerShell commands that can be used to run bat files, and advanced techniques and best practices for running batch files from PowerShell.

Mastering these techniques allows you to integrate and orchestrate batch workflows entirely within PowerShell scripts. By following these techniques and best practices, we can create efficient and reliable scripts that automate our tasks. So go ahead, create a PowerShell script or a batch file and take control of your automated tasks!

Further Reading

There are many ways to run a script from a batch file or a PowerShell script. Whether you wish to run a bat file from PowerShell script or run a PowerShell script from the batch file, the steps outlined above should provide a solid starting point. But don’t stop here! Expand your knowledge with these related posts:

How do I execute a .bat file within a PowerShell script?

To execute a .bat file from a PowerShell job, you can use the Start-Process cmdlet in PowerShell. Here’s an example:
Start-Process -FilePath "C:\path\to\file.bat"
By adding the batch file to a PowerShell script, you can have the batch file and PowerShell script run automatically when the PowerShell script executes.

Are batch files run in CMD or PowerShell?

Batch files are typically run in the Command Prompt (CMD) on Windows operating systems. However, they can also be run in PowerShell, which is a more advanced and powerful command-line shell and scripting language.

How to run a PowerShell command using a batch file?

To run a PowerShell command using the batch file, you can use the “powershell.exe” command followed by the PowerShell command you want to execute. For example, you can create a batch file with the following content:
@echo off
powershell.exe -Command "Get-Process"

How to run an Administrator command prompt from a batch file?

To run an Administrator command prompt from a batch file, you can use the runas command to run the batch file as an administrator. Here’s how you can do it:
@echo off
runas /user:Administrator "cmd /c C:\Temp\BackupDb.bat"

How to run PowerShell as admin from batch?

To run PowerShell as an administrator from a batch file, you can use the Start-Process cmdlet with the -Verb RunAs parameter to launch PowerShell with elevated privileges. Here’s how you can do it:
@echo off
powershell.exe -Command "Start-Process PowerShell -Verb RunAs"

How to run a batch file in PowerShell silently?

To run a batch file silently in PowerShell, you can use the Start-Process cmdlet with the -WindowStyle Hidden parameter or NoNewWindow switch. This will launch the batch file without displaying a window. Here are the examples:
Start-Process -FilePath "C:\path\to\batchfile.bat" -WindowStyle Hidden
Start-Process -FilePath "C:\temp\Backup-Database.bat" -NoNewWindow

What is the difference between batch files and PowerShell?

Batch files and PowerShell are both scripting languages used for automating tasks, but there are some key differences between them. Batch files are simpler and more limited in functionality, while PowerShell is more powerful and versatile. PowerShell also has more advanced features and can interact with the .NET framework.

How do I run multiple PowerShell scripts from a batch file?

To run multiple PowerShell scripts from a batch file, you can use the “call” command followed by the path to each PowerShell script. For example, if you have two PowerShell scripts named “script1.ps1” and “script2.ps1”, your batch file would include the following lines:
@echo off
echo Running PowerShell scripts…
call powershell.exe -ExecutionPolicy Bypass -File "C:\temp\script1.ps1"
call powershell.exe -ExecutionPolicy Bypass -File "C:\temp\script2.ps1"
echo Done.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *