Call PowerShell script PS1 from another PS1 script inside Powershell ISE
I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE.
The following code inside MyScript2.ps1, works fine from Powershell Administration, but doesn't work inside PowerShell ISE:
#Call myScript1 from myScript2
invoke-expression -Command .\myScript1.ps1
I obtain the following error when I execute MyScript2.ps1 from PowerShell ISE:
The term '.\myScript1.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path
(make sure you use this in the script context).
The reason you should use that and not anything else can be illustrated with this example script.
## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path
Here are some results.
PS C:\Users\JasonAr> .\ScriptTest.ps1 InvocationName: .\ScriptTest.ps1 Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> . .\ScriptTest.ps1 InvocationName: . Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> & ".\ScriptTest.ps1" InvocationName: & Path: C:\Users\JasonAr\ScriptTest.ps1
In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot
:
## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1 Script: C:\Users\jarcher\ScriptTest.ps1 Path: C:\Users\jarcher
I am calling myScript1.ps1 from myScript2.ps1 .
Assuming both of the script are at the same location, first get the location of the script by using this command :
$PSScriptRoot
And, then, append the script name you want to call like this :
& "$PSScriptRoot\myScript1.ps1"
This should work.
The current path of MyScript1.ps1 is not the same as myScript2.ps1. You can get the folder path of MyScript2.ps1 and concatenate it to MyScript1.ps1 and then execute it. Both scripts must be in the same location.
## MyScript2.ps1 ##
$ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\MyScript1.ps1"
One line solution:
& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")