Powershell

How to Run a PowerShell Script From a Batch File

PowerShell script is a simple text file saved using the “.ps1” extension. It can be executed using the PowerShell ISE software. On the other hand, a BAT file is referred to as a text file that has a “.BAT” extension. More specifically, the Command Prompt can be used to run the BAT file. However, there can be a scenario where running the PowerShell script using the Batch file is required.

This post will explain the method for executing the batch file’s PowerShell script.

How to Run a PowerShell Script from a Batch File?

To run the PowerShell script from the batch file, follow the below-given guide.

Step 1: Create a PowerShell Script

In case you don’t have the script stored on your computer, then check the instruction to create it.

First, open PowerShell ISE, write the given code, and then, to save the file, hit the “Save” button:

write-output "Car"

Write-output "Bike"

Write-Output "Cycle"

Write-output "Bus"

Write-output "Airplane"

Write the script name and save it with the “.ps1” file extension at the end. Finally, to save script, press the “Save” button:

Step 2: Create a Batch File

After creating a PowerShell script, create the Batch file. For that reason, open “Notepad” and write the given line of code:

  • First, write the “@echo off” command.
  • In the second line, write “powershell.exe” and then write the PowerShell script file path within inverted commas.
  • Add the timer to terminate the Command Prompt console after a specified time.
  • Lastly, save the file with “.Bat” file extension:
@echo off

powershell.exe ". 'C:\Users\Muhammad Farhan\Documents\Script.ps1' "

TIMEOUT /T 5

Here:

  • @echo off” command is used to hide the file path specified in the Command Prompt console.
  • TIMEOUT” is used to wait for the specified seconds before closing the batch file.
  • powershell.exe” is utilized to specify the PowerShell for running the script file.

Step 3: Execute a Batch File

Now, execute the batch file by writing its complete file path with inverted commas:

>"C:\Users\Muhammad Farhan\Desktop\testing.bat"

The output shows that the PowerShell script has been executed from a batch file.

Conclusion

To run the PowerShell script from the batch file, first open “Notepad”, write the batch file script inside it, and specify the PowerShell script file path. Then, save it with the “.BAT” extension and execute it by double-clicking on the batch file. Moreover, it can also be executed by writing the PowerShell script file path in the CMD console within inverted commas. This post has demonstrated a complete method for executing the PowerShell script from a batch file.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.