Reputation: 25954
When debugging Powershell, what is the difference between local vs script in VSCode?
I have looked for the current folder, calling a module(psm1) and it confused me that $PSScriptRoot
did not give the right path.
I have a main.ps1
importing some module.psm1
.
In root folder(myroot), main.ps1:
-- Import-Module sub/module.psm1`
module.psm1:
...
Get-Folder() {return $PSScriptRoot}
..
This gives me the folder myroot/sub the modules folder , but if I do: module.psm1:
...
Get-Folder() {return $local:MyInvocation.PSScriptRoot}
...
Then I get the right folder myroot calling the modul - so basically:
$local:MyInvocation.PSScriptRoot
vs
$script:MyInvocation.PSScriptRoot
vs
$PSScriptRoot
Upvotes: 1
Views: 513
Reputation: 10019
From the about_automatic_variables documentation:*
Unlike the $PSScriptRoot and $PSCommandPath automatic variables, the PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.
From the about_scopes documentation:*
Local: The current scope. The local scope can be the global scope or any other scope.
Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.
Combining these gives you the behavior you're seeing.
So basically if you want to find out the location of the currently running code, use $PSScriptRoot
.
If you want to find out what's calling that code, use $MyInvocation.PSScriptRoot
.
The $local:
scope modifier will give you this from the currently running code, the $script:
modifier will list the location of last calling script (i.e. these will be different if you called a function in another module from module.psm1
because $local:
will refer to module.psm1
location and $script:
will refer to main.ps1
location, as main.ps1
is the calling script).
If it still doesn't make sense, let me know and I'll put together some demo scripts.
*emphasis added
Upvotes: 3