In this article, I’ll show you how to run PowerShell script from batch file and how you can run all the PowerShell scripts that exist in a particular folder using a batch file.
So let’s start first with how you can run a PowerShell script from the batch file.
Run PowerShell script from batch file
To run a PowerShell script from a batch file, you can use the “start” command with the “powershell.exe” command and the “-File” parameter, followed by the path to the script file.
start powershell.exe -File "c:\psscript\currentdate.ps1”
We have one psscript folder where I have one “currentdate.ps1” PowerShell script when we execute that script it will print the current date on the console.
Note-You can hold the screen for some seconds to see the output window. Like I have paused the screen for 20 seconds.
You can also use the “Start-Process” cmdlet in PowerShell to start a new process and run the script see the below example –
Start-Process powershell.exe -ArgumentList "-File ""c:\psscript\currentdate.ps1"""
And if the PowerShell script requires any input parameters, you can pass that after the script name like below-
start powershell.exe -File "c:\psscript\currentdate.ps1" -param1 value1 -param2 value2
Remember one thing, if you’re running the script from a different directory, you’ll need to use the full path to the script file.
It’s also important to mention that if your script needs to run with elevated permissions, you’ll need to run the batch file as an administrator, or use the “runas” command to run it with specific credentials, like below –
runas /user:username "powershell.exe -File ""c:\psscript\currentdate.ps1"""
Note- Don’t forget to change the script path with your script path.
One more thing here, if your script needs to access some external resources like the network, you may need to set the execution policy to allow scripts to run before you can execute them.
powershell.exe -ExecutionPolicy Unrestricted -File " c:\psscript\currentdate.ps1"
Note – This is optional, run this command only if you are getting an execution policy exception.
This is how you can run the PowerShell script from batch file but this only works for a single “.ps1” file. What if you have to run a bunch of PowerShell scripts exists in a particular directory/folder?
Batch file runs all PowerShell scripts in the current directory
To run all PowerShell scripts in a specific directory from a batch file, you can use a for loop to iterate through the files in the folder and execute each script using the “powershell.exe” command and the “-File” parameter.
for /f "tokens=*" %%f in ('dir "c:\psscript\*.ps1" /b') do ( powershell.exe -File "c:\psscript\%%f" )
This will run all the files with the .ps1 extension in the folder “c:\psscript\”.
This is how you can run a PowerShell script from batch file. Also, I show you how batch files run all PowerShell scripts in the current directory or from a specific folder.