How can I get the file system location of a PowerShell script?

PowershellBatch File

Powershell Problem Overview

I have a PowerShell script located at D:\temp.

When I run this script, I want the current location of the file to be listed. How do I do this?

For example, this code would accomplish it in a DOS batch file; I am trying to convert this to a PowerShell script...

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"

Powershell Solutions

Solution 1 - Powershell

PowerShell 3+

The path of a running scripts is:


Its directory is:


PowerShell 2

The path of a running scripts is:


Its directory is:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent

Solution 2 - Powershell

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.

Solution 3 - Powershell

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"


P.S. Included full error handling. Adjust to your needs, accordingly.

Solution 4 - Powershell

Here is one example:

$ScriptRoot = ($ScriptRoot, "$PSScriptRoot" -ne $null)[0]
import-module $ScriptRoot\modules\sql-provider.psm1
Import-Module $ScriptRoot\modules\AD-lib.psm1 -Force


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSanthoshView Question on Stackoverflow
Solution 1 - PowershellRoman KuzminView Answer on Stackoverflow
Solution 2 - PowershellstejView Answer on Stackoverflow
Solution 3 - PowershellQuantiumView Answer on Stackoverflow
Solution 4 - Powershelllive-loveView Answer on Stackoverflow