How to execute a .ps1 from another .ps1 file?
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?
14 Answers
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.ps1the 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"
& $scriptIf 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 i got this from a different article but it can apply here: thanks ()
First, if you want to make multiple calls in a single session to a remote machine, first create a PSSession:
$session = New-PSSession -ComputerName $ComputerNameThen 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 $sessionalso 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