Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call another PowerShell script with a relative path?

I have the following directory tree:

e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1

and now I'd like to call a script named "Press any key to continue.ps1" that sits in the "utils"-folder from a script that I have in the "services"-folder. How do I do that? I cannot figure out the relative path.

I tried to do it this way:

"$ '.\..\utils\Press any key to continue.ps1'"

but it did not work.

like image 536
t3chb0t Avatar asked Sep 11 '11 11:09

t3chb0t


People also ask

How do I run a PowerShell script from another PowerShell script?

You don't need Start-Process. PowerShell scripts can run other scripts. Just put the command that runs the second script as a command in the first script (the same way as you would type it on the PowerShell command line).

How do I run a PowerShell script from the path?

To run a script on one or more remote computers, use the FilePath parameter of the Invoke-Command cmdlet. Enter the path and filename of the script as the value of the FilePath parameter. The script must reside on the local computer or in a directory that the local computer can access.

What is relative path in PowerShell?

For example, if the file in question lives at absolute path C:\Users\MyUsername\Desktop\test. txt, and I decide that the root directory is C:\Users\MyUsername, the relative path would be Desktop\test. txt, which is what should be stored in the CSV.


3 Answers

Based on what you were doing, the following should work:

& "..\utils\Press any key to continue.ps1"

or

. "..\utils\Press any key to continue.ps1"

(lookup the difference between using & and . and decide which one to use)

This is how I handle such situations ( and slight variation to what @Shay mentioned):

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$utilsDir  = Join-Path -Path $scriptDir -ChildPath ..\utils

& "$utilsDir\Press any key to continue.ps1"
like image 117
manojlds Avatar answered Oct 23 '22 14:10

manojlds


Put the following function in the calling script to get its directory path and join the utils path along with the script name:

# create this function in the calling script
function Get-ScriptDirectory { Split-Path $MyInvocation.ScriptName }

# generate the path to the script in the utils directory:
$script = Join-Path (Get-ScriptDirectory) 'utils\Press any key to continue.ps1'

# execute the script
& $script 
like image 24
Shay Levy Avatar answered Oct 23 '22 16:10

Shay Levy


To get the current script path $PSScriptRoot variable can be used. for example Following is the structure: solution\mainscript.ps1 solution\secondscriptfolder\secondscript.ps1

#mainscript.ps1

$Second = Join-Path $PSScriptRoot '\secondscriptfolder\secondscript.ps1'

$Second
like image 5
Captain_Levi Avatar answered Oct 23 '22 14:10

Captain_Levi