有没有办法覆盖 powershell 中的“~”(波形符)位置

Roä*_*oäc 2 powershell environment-variables

问题

我试图~在 PowerShell 中更改字符的扩展路径而不更改$Env:USERPROFILE变量。

我尝试过的

我最初的方法是为引用不同环境变量的函数创建一个别名,但它似乎不起作用。

我的代码:

function Get-HomeDirectory { 
  # This is a custom function, it works as I have tested it
  # It should be self-explanatory
  Get-EnvironmentVariable -Key $HOME_DIR_KEY -User
}
Set-Alias -Name ~ -Value Get-HomeDirectory
Run Code Online (Sandbox Code Playgroud)

结果

如果我使用 Get-Help 它会按预期工作:

PS> Get-Help ~                                                                                                                                                                            

NAME
    Get-HomeDirectory

SYNOPSIS
    Returns the home directory of the current user.


SYNTAX
    Get-HomeDirectory [<CommonParameters>]


DESCRIPTION
    Retrieves the value set for the `$Env:USER_HOME_DIR` environment variable.


RELATED LINKS
    Set-HomeDirectory

REMARKS
    To see the examples, type: "Get-Help Get-HomeDirectory -Examples"
    For more information, type: "Get-Help Get-HomeDirectory -Detailed"
    For technical information, type: "Get-Help Get-HomeDirectory -Full"
    For online help, type: "Get-Help Get-HomeDirectory -Online"
Run Code Online (Sandbox Code Playgroud)

但如果我尝试使用它,我会得到:

PS> cd ~
PS> pwd
C:\Users\myuser
Run Code Online (Sandbox Code Playgroud)

什么可以正常工作

尽管如此,如果我用管道传递它(应该如此),我就可以让它工作,但这不是一种非常方便的使用方式:

PS> ~ | cd
PS> pwd

Path
----
B:\
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 5

使用函数(通过别名)~在参数中重新定义是行不通的(除非函数调用包含在 中(...)),原因在 Jeroen Mostert 对您的问题的评论中进行了解释。

一个解决方案,但请注意,它重新定义了文件系统提供程序路径会话全局中的初始值(提供程序~主位置的占位符,仅由提供程序 cmdlet解释)的含义。

# Make the file-system provider use the value of
# env. var. USER_HOME_DIR as its home location.
(Get-PSProvider FileSystem).Home = $Env:USER_HOME_DIR
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 更改仅对当前会话生效;为了使其持久化,您必须将其添加到您的$PROFILE文件中 - 但请注意,可以通过 CLI 的参数绕过配置文件的加载-NoProfile

  • 每个提供商都有自己的(可能未定义的)家庭位置。因此,在非典型情况下,当前位置下的提供者不是文件系统提供者,~则指的是提供者的主位置;一个人为的例子:

    # !! Fails, because the function provider has no home location defined. 
    Set-Location Function:; Get-Item ~
    
    Run Code Online (Sandbox Code Playgroud)