22

I have two PowerShell files. a.ps1 and b.ps1.

At a center point in a.ps1 I want to start executing code in b.ps1 and terminate a.ps1 script.

How to do it considering that both files are located in the same folder?

1
  • at the moment I am using PS 'path file' with no success
    – GibboK
    Feb 24, 2015 at 10:58

4 Answers 4

4

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.

42

In a.ps1,

& .\b.ps1

the way you invoke other programs

3

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
0

i got this from a different article but it can apply here: thanks (https://stackoverflow.com/users/3905079/briantist)

First, if you want to make multiple calls in a single session to a remote machine, first create a PSSession:

$session = New-PSSession -ComputerName $ComputerName

Then use that session in all subsequent calls:

Invoke-Command -Session $session -File $filename
Invoke-Command -Session $session -ScriptBlock {
# Some code

} Then close the session when you're done:

Remove-PSSession -Session $session

also if you don't know exactly ware that script will be but know whare your script starts u can do this:

$strInst = Get-ChildItem -Path $PSScriptRoot -Filter Import-Carbon.ps1 -recurse -ErrorAction SilentlyContinue -Force | Select Directory
Invoke-Experssion (start Powershell ($strinst\Import-Carbon.ps1)

(thats mine)

1
  • 2
    This is needlessly complicated and doesn't address the question.
    – Orangutech
    Jan 7, 2021 at 0:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .