Skip to content

Instantly share code, notes, and snippets.

@aniston
Forked from glombard/Get-ScriptPath.ps1
Created February 8, 2017 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniston/cef801ce37ad8064c53261977ce1da74 to your computer and use it in GitHub Desktop.
Save aniston/cef801ce37ad8064c53261977ce1da74 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment