2
votes

I have a script which calls two other scripts.

script0.ps1

Invoke-Expression C:\script1.ps1
Invoke-Expression C:\script2.ps1

The first script starts a web server:

script1.ps1

./activate anaconda_env     
cd C:\webserver
python api_server.py

The second script starts a ngrok service:

script2.ps1

./activate anaconda_env
cd c:\ngrok
./ngrok -subdomain=mysd 8000

The problem is that the script0.ps1 only executes script1.ps1. At this point the web server starts running in the console and so the second command of script0.ps1 is not executed.

How to make write the scripts so both commands are executed? Or, how to write just one script to execute all commands but in two separate consoles?

The final result should be: 1) a web server running in a console with activated anaconda environment 2) a ngrok service running in a console with with activated anaconda environment

3
What have you tried so far? Can you not simply have two functions in the script then execute them or execute a main function that fires the other two? - CalebB

3 Answers

0
votes

Change Script1.ps1 to launch python as a job:

./activate anaconda_env     
 cd C:\webserver
 Invoke-Command -ScriptBlock {.\python.exe api_server.py} -AsJob -ComputerName .

I don't have the specific script you're using, so I tested this with turtle.py which ships with 3.43 and it seems to work.

0
votes

You don't need to use Invoke-Expression to run a Powershell script from another script. Just run it as if you're on the command line

c:\script1.ps1
c:\script2.ps1

Now if script1.ps1 starts a process that doesn't exit, it will halt execution for the next statements in the script, and thus also prevent the second script from running. In most cases this sequential execution is exactly what you want.

In your case you can start the scripts asynchronously by using Start-Process. So your main script becomes something like:

start-process c:\script1.ps1
start-process c:\script2.ps1

Start-Process basically starts a new command shell to run the statement in. Check out the docs for more info. There's a bunch of parameters you can use to tweak how this happens.

-1
votes

To not have invoke-expression close your script you can pipe the output to Out-Null. Your code above would look like:

Invoke-Expression C:\script1.ps1 | Out-Null
Invoke-Expression C:\script2.ps1 | Out-Null