How to execute a .ps1 from another .ps1 file?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 How To Execute A .Ps1 From Another .Ps1 File?
00:22 Accepted Answer Score 4
00:44 Answer 2 Score 43
00:55 Answer 3 Score 0
01:31 Answer 4 Score 3
01:52 Thank you
--
Full question
https://superuser.com/questions/881853/h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#powershell #window
#avk47
ANSWER 1
Score 43
In a.ps1,
& .\b.ps1
the way you invoke other programs
ACCEPTED ANSWER
Score 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.
ANSWER 3
Score 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
ANSWER 4
Score 0
I got this from StackOverflow but it can apply here: (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
If you don't know exactly where that script will be but know where your script starts, you 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)