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
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")
To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:
# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))
# Execute script at location:
&"$ScriptRoute"
This is just additional info to answers in order to pass argument into the another file
Where you expect argument
PrintName.ps1
Param(
[Parameter( Mandatory = $true)]
$printName = "Joe"
)
Write-Host $printName
How to call the file
Param(
[Parameter( Mandatory = $false)]
$name = "Joe"
)
& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name
If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the "Joe" string
I had a problem with this. I didn't use any clever $MyInvocation
stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit
then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax.
My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts.
When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...