Relative File Paths in Powershell
My first intensive use of PowerShell was for scripting software installations/configurations. From development to deployment, I couldn’t guarantee the absolute file path of my script and any supporting files would be constant. I needed my script to be able to figure out where the supporting files were in relation to itself.
Here are a few suggestions how to solve the problem.
VAR1: $PSScriptRoot (state of the art)
$PSScriptRoot is an Automatic Variable, which are built-in variables that contain information about the PowerShell environment itself. $PSScriptRoot contains the directory path of the script being executed currently. Originally $PSScriptRoot was only applicable to script modules (.psm1), but beginning with PowerShell 3.0, it works for all PowerShell script files.
From the console if I type $PSScriptRoot and press ENTER, it returns nothing. $PSScriptRoot only gets a value when a script is executing, and then is destroyed when the script terminates.
The problem is, that it won't work from Visual Code or PowerShell ISE (IDE Environment)
# DemoScript.ps1
$configFilePath = $PSScriptRoot + "\DemoFile.cfg"
Write-Host $configFilePath
VAR2: $MyInvocation.MyCommand.Path (old way)
If there is no option to use PowerShell 3.0 or higher you have to use another Automatic Variable, $MyInvocation.MyCommand.Path
It can be used in the same fashion as $PSScriptRoot.
# DemoScript.ps1
$scriptPath = split-path -parent $MyInvocation.MyCommand.Path
$configFilePath = $scriptPath + "\DemoFile.cfg"
Write-Host $configFilePath
VAR3: My preferred way
# Query Scriptpath
$PathToScript = Switch ($Host.name){
'Visual Studio Code Host' { split-path $psEditor.GetEditorContext().CurrentFile.Path }
'Windows PowerShell ISE Host' { Split-Path -Path $psISE.CurrentFile.FullPath }
'ConsoleHost' { $PSScriptRoot }
}
# Tested on Windows in PS 5.1.
Reference: