How to execute a .ps1 from another .ps1 file?

Is it ok if b.ps1 is executed in a new Power Shell process? If so the following should do what you describe.

Invoke-Item (start powershell ((Split-Path $MyInvocation.InvocationName) + "\b.ps1"))

"Invoke-Expression" executes in the same process but waits for termination of b.ps1.


In a.ps1,

& .\b.ps1

the way you invoke other programs


Use the magic variable $PSScriptRoot to refer to your current directory. Then call script B with the ampersand ("Call operator"):

$script = $PSScriptRoot+"\b.ps1"
& $script

If you want to keep the variables from B in scope of A, you can run the script using the Dot sourcing operator:

$script = $PSScriptRoot+"\b.ps1"
. $script