klyd
klyd

Reputation: 3979

Get the path of the importing script from within a module?

Is there a way to get the path of a script that imported a module from within that module?

The script module I'm writing is meant to load settings from files relative to the importing script. I plan on reusing the module for a number of projects, so I would prefer if the module could make no assumptions about where its being imported from.

This is a nice to have, it would be great the module could be as implicit as possible. If all else fails though, I can just have the caller pass in its location.

Unfortunately everything I've attempted so far returns the path to the module (not what imported it). Here's a simple demonstration:


Test-RelativeModule.ps1, Stored at: c:\test\

import-module "$PSScriptRoot\mod\Test.psm1"

Test.psm1, Stored at: c:\test\mod\

# returns 'c:\test\mod'
write-host "`$PSScriptRoot: $PSScriptRoot"

# returns 'c:\test\mod'
# The value of $MyInvocation.MyCommand.Path is 'c:\test\mod\Test.psm1'
write-host "Split Invoation: $(Split-Path $MyInvocation.MyCommand.Path)"

# returns whatever path the console is currently residing
write-host "Resolve Path: $((resolve-path '.\').path)"

# what I'm looking for is something to return 'c:\test' from within the module
# without making any assumptions about the folder structure

Upvotes: 5

Views: 4126

Answers (1)

Keith Hill
Keith Hill

Reputation: 201692

Try this:

Write-Host "My invoker's PSScriptRoot: $($MyInvocation.PSScriptRoot)"

Upvotes: 7

Related Questions