PowerShell中定义的默认别名在哪里?

Xer*_*ion 7 powershell

这可能是一个愚蠢的问题,但是在PowerShell中是硬编码的默认别名(例如cd)还是在某个隐藏的"配置文件"脚本中定义的?

我没有设置任何配置文件(每个用户或系统范围),所以我只是想知道默认的来源.

Jay*_*uzi 10

它们是"内置的"但不是一成不变的.注意:

PS>(Get-Alias dir).选项
AllScope
PS>(Get-Alias gci).选项
ReadOnly,AllScope

PS> Get-Alias | 组选项

计数名称组 ----- ---- ----- 91 ReadOnly,AllScope {%,?,ac,asnp ...} 46 AllScope {cat,cd,chdir,clear ...}

如您所见,该ReadOnly选项对别名进行了一些分区.这些ReadOnly在PowerShell中是惯用的,而可变的则是熟悉其他shell的人.我见过人们修改dir添加更多功能,同时保持gci直接别名Get-ChildItem.

为了广泛的兼容性,我只ReadOnly在脚本中使用别名.

另外,因为dir在CMD,lsUNIX和gciPowerShell中,每个都以自己的方式工作,我训练自己使用本机命令,而不是别名.dir往往会到处工作,但dir -Recurse不是!

作为一个训练练习,并测试我的脚本的兼容性,我有时会删除非ReadOnly别名:

Get-Alias | ? { ! ($_.Options -match "ReadOnly") } | % { Remove-Item alias:$_ }
Run Code Online (Sandbox Code Playgroud)

有一个更温和的方法,你用一个新命令替换每个别名,警告你正在使用其中一个兼容性别名,但让你继续运行.

此外,您可以根据需要更改ReadOnly别名,但出于上述原因,我建议不要使用它:

PS> Set-Alias -Name sl -Value Get-ChildItem -Force -Option AllScope #BAD!
PS> sl

目录:C:\ Users\Jay

模式LastWriteTime长度名称 ---- ------------- ------ ----


x0n*_*x0n 7

硬编码,但可检索(像PowerShell中的大多数"隐藏")

PS> [Management.Automation.Runspaces.InitialSessionState].getproperty(
        "BuiltInAliases", [reflection.bindingflags]"NonPublic,Static").getvalue(
             $null, @()) | format-table -auto

Definition           Description            Options CommandType Visibility Name    PSSnapIn Module
----------           -----------            ------- ----------- ---------- ----    -------- ------
Add-Content                      ReadOnly, AllScope       Alias     Public ac
Add-PSSnapIn                     ReadOnly, AllScope       Alias     Public asnp
Clear-Content                    ReadOnly, AllScope       Alias     Public clc
Clear-Item                       ReadOnly, AllScope       Alias     Public cli
Clear-ItemProperty               ReadOnly, AllScope       Alias     Public clp
Clear-Variable                   ReadOnly, AllScope       Alias     Public clv
...
Run Code Online (Sandbox Code Playgroud)

;-)

  • get-alias当然也可以工作,但上面的代码是明确的,无论其他模块/ snapins添加它们自己的混合. (2认同)