How to get the current directory of the cmdlet being executed

后端 未结 17 2107
滥情空心
滥情空心 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:54

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

    (Get-Item .).FullName
    
    0 讨论(0)
  • 2020-11-29 17:55

    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
    
    0 讨论(0)
  • 2020-11-29 17:55

    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.

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

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

    In Powershell 3 and above you can simply use

    $PSScriptRoot

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