How to get the current directory of the cmdlet being executed

后端 未结 17 2225
滥情空心
滥情空心 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("\"));
        }
    }
    

提交回复
热议问题