In my PowerShell script Main.ps1
I need to access a variable $script_name
or $script_path
to return the name and path of this running script.
Elsewhere, I have seen something like this:
$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.TrimEnd("\"+$currentScriptName)
This works well. But does it mean I need to place this much text in each and every script where I want to automatically get the current script's name and path?
I thought about placing those 3 lines in another script (named Variables.ps1
and dot sourcing it anywhere else it is needed. Like so:
# Main.ps1
. ".\Variables.ps1"
Write-Host $currentScriptName
Unfortunately this still prints "Variables.ps1"
Placing the 3 lines of code in the current profile script is even worse. Of course, the profile script variables are run and fossilized as the console is launched, and something like this: $current_time = Get-Date
or $var = [ANY WINDOWS ENVIRONMENT VARIABLE]
when placed in the profile, will always return the time the console was launched, even when the calling script is running one week later!
So my question is: How can I most concisely re-use such a variable (with dynamic value) in my scripts by declaring it elsewhere, such that when called, it "determines" its value at the point of being called.