Skip to content

Instantly share code, notes, and snippets.

@aniston
Forked from glombard/Get-ScriptPath.ps1
Last active March 5, 2023 07:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniston/c3a7d2f1cc2e1a73c62d5d95a5969d84 to your computer and use it in GitHub Desktop.
Save aniston/c3a7d2f1cc2e1a73c62d5d95a5969d84 to your computer and use it in GitHub Desktop.
Use different techniques to determine a PowerShell script's directory: try `$PSScriptRoot`, `$MyInvocation.MyCommand.Path`, `$ExecutionContext.SessionState.Module.Path` and `$PWD`.
function Get-ScriptPath {
$scriptDir = Get-Variable PSScriptRoot -ErrorAction SilentlyContinue | ForEach-Object { $_.Value }
if (!$scriptDir) {
if ($MyInvocation.MyCommand.Path) {
$scriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
}
}
if (!$scriptDir) {
if ($ExecutionContext.SessionState.Module.Path) {
$scriptDir = Split-Path (Split-Path $ExecutionContext.SessionState.Module.Path)
}
}
if (!$scriptDir) {
$scriptDir = $PWD
}
return $scriptDir
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment