Calling powershell script from batch file

By FoxLearn 10/1/2024 9:45:02 AM   2
To call a PowerShell script from a batch file, you can use the powershell.exe command followed by the -File parameter.

How to run a PowerShell script from a batch file?

First, You need to create a PowerShell script file (e.g., script.ps1).

For example:

Write-Host "Hello from PowerShell!"

Next, create a batch file (e.g., run_script.bat) to call the PowerShell script.

For example:

@echo off
powershell.exe -ExecutionPolicy Bypass -File "C:\path\to\your\script.ps1"
pause

You need the -ExecutionPolicy parameter.

If you don't use the -File parameter when calling a PowerShell script, PowerShell interprets the entire line as a command to execute. Since Set-ExecutionPolicy is a cmdlet and doesn't have a -File parameter, this leads to an error. Always specify -File when executing scripts to avoid this issue.

  • @echo off: Prevents the commands from being displayed in the command prompt.
  • powershell.exe: Calls the PowerShell executable.
  • -ExecutionPolicy Bypass: Temporarily bypasses the execution policy, allowing your script to run even if it’s not signed.
  • -File "C:\path\to\your\script.ps1": Specifies the path to your PowerShell script.
  • pause: Keeps the command prompt open so you can see any output before it closes.

To execute the batch file, simply double-click it, and it should run the PowerShell script.