Skip to content

Instantly share code, notes, and snippets.

@glombard
Created May 2, 2014 10:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save glombard/1ae65c7c6dfd0a19848c to your computer and use it in GitHub Desktop.
Save glombard/1ae65c7c6dfd0a19848c 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 {
$scritDir = 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
}
@BartVandyck
Copy link

I think you made a small typo on de second line. I should be " $Scriptdir = ....... "

@pwozniak
Copy link

Only $PWD.Path works for me.

@bartonjd
Copy link

bartonjd commented May 3, 2018

there is a typo on line 2, it should be $scriptDir not $scritDir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment