How to get the current directory of the cmdlet being executed

安稳与你 提交于 2019-11-27 06:16:54

The reliable way to do this is just like you showed $MyInvocation.MyCommand.Path.

Using relative paths will be based on $pwd, in PowerShell, the current directory for an application, or the current working directory for a .NET API.

PowerShell v3+:

Use the automatic variable $PSScriptRoot.

GuruKay

Yes that should work. But if you need to see the absolute path, this is all you need:

(Get-Item -Path ".\").FullName
Tony Sheen

The easiest method seems to be to use the following predefined variable:

 $PSScriptRoot

about_Automatic_Variables and about_Scripts both state:

In PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in PowerShell 3.0, it is valid in all scripts.

I use it like this:

 $MyFileName = "data.txt"
 $filebase = Join-Path $PSScriptRoot $MyFileName

You can also use:

(Resolve-Path .\).Path

The part in brackets returns a PathInfo object.

(Available since PowerShell 2.0.)

Path is often null. This function is safer.

function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
    if($Invocation.PSScriptRoot)
    {
        $Invocation.PSScriptRoot;
    }
    Elseif($Invocation.MyCommand.Path)
    {
        Split-Path $Invocation.MyCommand.Path
    }
    else
    {
        $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
    }
}
Rohin Sidharth

Try :

(Get-Location).path

or:

($pwd).path
Veera Induvasi

Get-Location will return the current location:

$Currentlocation=Get-Location

I like the one line solution :)

$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
Sevenfold Exurbanite

Try this:

$WorkingDir = Convert-Path .

In Powershell 3 and above you can simply use

$PSScriptRoot

You would think that using '.\' as the path means that it's the invocation path. But not all the time. Example, if you use it inside a job ScriptBlock. In which case, it might point to %profile%\Documents.

For what its worth to be a single line of solution, the below is a working solution for me.

$currFolderName = (Get-Location).Path.Substring((Get-Location).Path.LastIndexOf("\")+1)

the 1 at the end is to ignore the /.

thanks to the posts above using Get-Location cmdlet

To expand on @Cradle 's answer: you could also write a multi-purpose function that will get you the same result per the OP's question:

Function Get-AbsolutePath {

    [CmdletBinding()]
    Param(
        [parameter(
            Mandatory=$false,
            ValueFromPipeline=$true
        )]
        [String]$relativePath=".\"
    )

    if (Test-Path -Path $relativePath) {
        return (Get-Item -Path $relativePath).FullName -replace "\\$", ""
    } else {
        Write-Error -Message "'$relativePath' is not a valid path" -ErrorId 1 -ErrorAction Stop
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!