問題
我正在嘗試在不更改變數~的情況下更改 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
結果
如果我使用 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"
但是如果我嘗試使用它,我會得到:
PS> cd ~
PS> pwd
C:\Users\myuser
什么作業正常
不過,如果我用管道傳遞它(應該如此),我可以讓它作業,但這不是一種非常方便的使用方式:
PS> ~ | cd
PS> pwd
Path
----
B:\
uj5u.com熱心網友回復:
由于 Jeroen Mostert 對您的問題的評論中解釋了原因,使用函式(通過別名)~在引數中重新定義是行不通的(除非函式呼叫包含在 中)。(...)
有一個解決方案,但請注意,它重新定義了首字母的含義- provider~的主位置的占位符,僅由 provider 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
筆記:
更改僅對當前會話生效;要使其持久化,您必須將其添加到您的
$PROFILE檔案中 - 但請注意,可以通過 CLI 的-NoProfile引數繞過加載組態檔。每個提供者都有自己的 - 可能未定義 - 家庭位置。因此,在當前位置的提供者不是檔案系統提供者的非典型事件中,
~指的是該提供者的主位置;一個人為的例子:# !! Fails, because the function provider has no home location defined. Set-Location Function:; Get-Item ~
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475908.html
