How can I get the file system location of a PowerShell script?
PowerShell 3+
The path of a running scripts is:
$PSCommandPath
Its directory is:
$PSScriptRoot
PowerShell 2
The path of a running scripts is:
$MyInvocation.MyCommand.Path
Its directory is:
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
Roman Kuzmin answered the question imho. I'll just add that if you import a module (via Import-Module
), you can access $PsScriptRoot
automatic variable inside the module -- that will tell you where the module is located.
For what it's worth, I found that this works for me on PowerShell V5 in scripts and in PowerShell ISE:
try { $scriptPath = $PSScriptRoot if (!$scriptPath) { if ($psISE) { $scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath } else { Write-Host -ForegroundColor Red "Cannot resolve script file's path" exit 1 } }} catch { Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)" exit 2}Write-Host "Path: $scriptPath"
HTH
P.S. Included full error handling. Adjust to your needs, accordingly.