1

$PSScriptRoot and $PSCommandPath are very useful in locating script files that are consumed by other scripts. Is there an easy, reliable way of getting the top-level script file that was actually executed? My users are right-clicking .ps1 files to execute them from File Explorer.

Example:

C:\Powershell\a.ps1
C:\Powershell\lib\b.ps1

I need a command that I can use from b.ps1 that preferably returns C:\Powershell\a.ps1, or at least C:\Powershell. $PSScriptRoot, $PSCommandPath, and $MyInvocation.MyCommand.Path all return C:\Powershell\lib\b.ps1, though.

Thanks!

2 Answers 2

1

This seems to work:

get-variable psscriptroot -scope ((get-pscallstack).count - 2)

That should get you the scriptroot in the fist child scope of the global scope, which would be the script scope of the initial script invocation.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice...I'm curious if this can be elegantly extended to accommodate N frames on the call stack.
It already does. No matter how far down the call stack you go, it will always reach back to the first child of the global scope and read the value of $PSScriptRoot from there.
0

Inside b.ps1, use the cmdlet:

Get-Location

This will return the parent path that you expect.

Why This Works: This works because you will navigate to the directory C:\Powershell\ and execute the script a.ps1 from there. When you execute . .\lib\b.ps1 you haven't left that execution location, so it will return exactly what you want.

Note: Note that this only works if you first navigate to the directory first, or for scheduled tasks you specify a "Start in" directory. So if you are in a different directory and execute your first script like this: C:\Powershell\a.ps1 it will return your other directory.

If you are really keen, more info on encapsulation is here: Further Down the Rabbit Hole PowerShell Modules and Encapsulation

1 Comment

Oh, sorry--I should have specified that a.ps1 refers to b.ps1 using its own directory from $PSCommandPath, rather than navigating to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.