To run a script, open a PowerShell window, type the script's name (with or without the . ps1 extension) followed by the script's parameters (if any), and press Enter.
Use CTRL+T to create a new powershell instance (a tab is created, which is called powershell 2, I believe) inside Powershell ISE. From the new Powershell tab you can now open a second powershell script and run it aside the script running in other powershell tabs.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With