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

14

3

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?

GibboK

Posted 2015-02-24T10:49:36.317

Reputation: 401

at the moment I am using PS 'path file' with no success – GibboK – 2015-02-24T10:58:25.113

Answers

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.

user2543253

Posted 2015-02-24T10:49:36.317

Reputation: 261

26

In a.ps1,

& .\b.ps1

the way you invoke other programs

chingNotCHing

Posted 2015-02-24T10:49:36.317

Reputation: 876

2

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)

Kelly Davis

Posted 2015-02-24T10:49:36.317

Reputation: 21

0

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

Ferro

Posted 2015-02-24T10:49:36.317

Reputation: 101