How to get the current directory of the cmdlet being executed

后端 未结 17 2105
滥情空心
滥情空心 2020-11-29 17:03

This should be a simple task, but I have seen several attempts on how to get the path to the directory where the executed cmdlet is located with mixed success. For instance,

相关标签:
17条回答
  • 2020-11-29 17:36

    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("\"));
        }
    }
    
    0 讨论(0)
  • 2020-11-29 17:39

    You can also use:

    (Resolve-Path .\).Path
    

    The part in brackets returns a PathInfo object.

    (Available since PowerShell 2.0.)

    0 讨论(0)
  • 2020-11-29 17:41

    Get-Location will return the current location:

    $Currentlocation = Get-Location
    
    0 讨论(0)
  • 2020-11-29 17:41

    Most answers don't work when debugging in the following IDEs:

    • PS-ISE (PowerShell ISE)
    • VS Code (Visual Studio Code)

    Because in those the $PSScriptRoot is empty and Resolve-Path .\ (and similars) will result in incorrect paths.

    Freakydinde's answer is the only one that resolves those situations, so I up-voted that, but I don't think the Set-Location in that answer is really what is desired. So I fixed that and made the code a little clearer:

    $directorypath = if ($PSScriptRoot) { $PSScriptRoot } `
        elseif ($psise) { split-path $psise.CurrentFile.FullPath } `
        elseif ($psEditor) { split-path $psEditor.GetEditorContext().CurrentFile.Path }
    
    0 讨论(0)
  • 2020-11-29 17:45

    I like the one-line solution :)

    $scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
    
    0 讨论(0)
  • 2020-11-29 17:47

    If you just need the name of the current directory, you could do something like this:

    ((Get-Location) | Get-Item).Name
    

    Assuming you are working from C:\Temp\Location\MyWorkingDirectory>

    Output

    MyWorkingDirectory

    0 讨论(0)
提交回复
热议问题