Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Powershell script from Batch script..But need the batch script to wait for the Powershell script to complete

I have a batch script being that has the following code in it:

Here is the batch script (Test.bat):

call powershell.exe -executionpolicy remotesigned -File TheScriptToBeExecuted.ps1

exit /b

The Powershell script (TheScriptToBeExecuted.ps1) has some wait built into it. But when this file is being called, the batch script is NOT waiting for the Powershell script to finish.

I ever tried:

START /wait powershell.exe -executionpolicy remotesigned -File TheScriptToBeExecuted.ps1

To no effect.

When I double click on the Test.bat file, it seems to be waiting. I have checked out a lot of answers, but couldnt find any that correspond to this issue.

Please help.

like image 597
NoRestartOnUpdate Avatar asked Oct 20 '25 13:10

NoRestartOnUpdate


2 Answers

start /wait powershell.exe -executionpolicy remotesigned -File TheScriptToBeExecuted.ps1 | ECHO > nul

Try the above. Holds the command until scripts executed, without the Teminate Batch Prompt. Use start /min /wait if not needing to display or interact with the script, or Alternately:

start /wait powershell.exe -executionpolicy remotesigned -WindowStyle Hidden -File TheScriptToBeExecuted.ps1 | ECHO > nul

-WindowStyle Value
Sets the window style for the session. Valid values are Normal, Minimized, Maximized and Hidden.

* | * pipes the output of the command, however as your just starting powershell.exe and not using it in the context of utilizing a command like follows, It shouldn't be an issue.

powershell -command "((Get-date).AddDays(0)).ToString(':dd:MM:yyyy') | set-content 'captureVar.txt'" && set /p Yesterday=<captureVar.txt

It worked for the script I tested, but it's not thoroughly tested. let me know how it goes.

like image 59
T3RR0R Avatar answered Oct 23 '25 02:10

T3RR0R


powershell -ExecutionPolicy ByPass -command ". 'C:\path\TheScriptToBeExecuted.ps1'"

This should do the it, if not then we will add < NUL to the end

powershell -ExecutionPolicy ByPass -command ". 'C:\path\TheScriptToBeExecuted.ps1'" < NUL

By using dot sourcing, we are opening powershell in the cmd window with the powershell reference in the above solution. Then the period allows the script to run in cmd window also. I did a double test and made a .ps1 with start-sleep -s 3 in it, and the above did wait for the powershell script to finish.

method 2 Using Start /wait

START /wait PowerShell.exe "& "'C:\path\TheScriptToBeExecuted.ps1'"

This method will not run inside the cmd window. It opens a powershell terminal and runs there then goes back to the bat.

like image 35
shadow2020 Avatar answered Oct 23 '25 04:10

shadow2020



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!