Где псевдонимы по умолчанию, определенные в PowerShell?
Это может быть глупый вопрос, но являются ли псевдонимы по умолчанию (например, cd) жестко закодированы в PowerShell или определены в скрытом скрипте "профиля" где-то?
У меня нет никаких профилей (для каждого пользователя или для всей системы), поэтому мне просто интересно, откуда берутся профили по умолчанию.
5 ответов
они "встроены", но не неизменны. Примечание:
PS > (Get-Alias dir).Options AllScope PS > (Get-Alias gci).Options ReadOnly, AllScopePS > Get-Alias | group Options
Count Name Group ----- ---- ----- 91 ReadOnly, AllScope {%, ?, ac, asnp...} 46 AllScope {cat, cd, chdir, clear...}
как вы можете видеть, существует некоторое разбиение псевдонимов на . The ReadOnly
они идиоматичны в PowerShell, в то время как изменяемые предназначены для людей, знакомых с другими оболочками. Я видел, как люди изменяют dir
чтобы добавить больше функциональности, сохраняя при этом gci
как прямой псевдоним для Get-ChildItem
.
для широкой совместимости я использую только ReadOnly
псевдонимы в моем файлы сценариев.
, потому что dir
в CMD,ls
в UNIX и gci
в PowerShell каждый работает по-своему, я тренируюсь использовать собственную команду, а не псевдоним. dir
имеет тенденцию работать везде, но dir -Recurse
не!
в качестве учебного упражнения и для проверки моих скриптов на совместимость я иногда удаляю не -ReadOnly
псевдонимы:
Get-Alias | ? { ! ($_.Options -match "ReadOnly") } | % { Remove-Item alias:$_ }
есть более мягкий подход, когда вы заменяете каждый псевдоним новой командой, которая предупреждает Вас, что вы используете один из псевдонимов совместимости, но позволяет сохранить функционирующие.
кроме того, вы можете изменить ReadOnly
aliases, если вы действительно хотите, но по вышеуказанным причинам я бы не рекомендовал это:
PS > Set-Alias -Name sl -Value Get-ChildItem -Force -Option AllScope # BAD! PS > slDirectory: C:\Users\Jay
Mode LastWriteTime Length Name ---- ------------- ------ ----
жестко закодированный, но извлекаемый (как и большинство вещей, "скрытых" в 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
...
;-)
хотя я не знаю технических деталей, я бы сказал, что они жестко запрограммированы и они не настраиваются. Они могут быть переопределены или удалены, но начальный набор не находится под нашим контролем.
другой способ найти встроенные псевдонимы, используя исходный код (C#) из GitHub:
internal static SessionStateAliasEntry[] BuiltInAliases {
get {
// Too many AllScope entries hurts performance because an entry is
// created in each new scope, so we limit the use of AllScope to the
// most commonly used commands - primarily so command lookup is faster,
// though if we speed up command lookup significantly, then removing
// AllScope for all of these aliases makes sense.
const ScopedItemOptions AllScope = ScopedItemOptions.AllScope;
const ScopedItemOptions ReadOnly_AllScope = ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope;
const ScopedItemOptions ReadOnly = ScopedItemOptions.ReadOnly;
return new SessionStateAliasEntry[] {
new SessionStateAliasEntry("foreach", "ForEach-Object", string.Empty, ReadOnly_AllScope),
new SessionStateAliasEntry("%", "ForEach-Object", string.Empty, ReadOnly_AllScope),
new SessionStateAliasEntry("where", "Where-Object", string.Empty, ReadOnly_AllScope),
new SessionStateAliasEntry("?", "Where-Object", string.Empty, ReadOnly_AllScope),
new SessionStateAliasEntry("clc", "Clear-Content", string.Empty, ReadOnly),
new SessionStateAliasEntry("cli", "Clear-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("clp", "Clear-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("clv", "Clear-Variable", string.Empty, ReadOnly),
new SessionStateAliasEntry("cpi", "Copy-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("cvpa", "Convert-Path", string.Empty, ReadOnly),
new SessionStateAliasEntry("dbp", "Disable-PSBreakpoint", string.Empty, ReadOnly),
new SessionStateAliasEntry("ebp", "Enable-PSBreakpoint", string.Empty, ReadOnly),
new SessionStateAliasEntry("epal", "Export-Alias", string.Empty, ReadOnly),
new SessionStateAliasEntry("epcsv", "Export-Csv", string.Empty, ReadOnly),
new SessionStateAliasEntry("fl", "Format-List", string.Empty, ReadOnly),
new SessionStateAliasEntry("ft", "Format-Table", string.Empty, ReadOnly),
new SessionStateAliasEntry("fw", "Format-Wide", string.Empty, ReadOnly),
new SessionStateAliasEntry("gal", "Get-Alias", string.Empty, ReadOnly),
new SessionStateAliasEntry("gbp", "Get-PSBreakpoint", string.Empty, ReadOnly),
new SessionStateAliasEntry("gc", "Get-Content", string.Empty, ReadOnly),
new SessionStateAliasEntry("gci", "Get-ChildItem", string.Empty, ReadOnly),
new SessionStateAliasEntry("gcm", "Get-Command", string.Empty, ReadOnly),
new SessionStateAliasEntry("gdr", "Get-PSDrive", string.Empty, ReadOnly),
new SessionStateAliasEntry("gcs", "Get-PSCallStack", string.Empty, ReadOnly),
new SessionStateAliasEntry("ghy", "Get-History", string.Empty, ReadOnly),
new SessionStateAliasEntry("gi", "Get-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("gl", "Get-Location", string.Empty, ReadOnly),
new SessionStateAliasEntry("gm", "Get-Member", string.Empty, ReadOnly),
new SessionStateAliasEntry("gmo", "Get-Module", string.Empty, ReadOnly),
new SessionStateAliasEntry("gp", "Get-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("gpv", "Get-ItemPropertyValue", string.Empty,ReadOnly),
new SessionStateAliasEntry("gps", "Get-Process", string.Empty, ReadOnly),
new SessionStateAliasEntry("group", "Group-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("gu", "Get-Unique", string.Empty, ReadOnly),
new SessionStateAliasEntry("gv", "Get-Variable", string.Empty, ReadOnly),
new SessionStateAliasEntry("iex", "Invoke-Expression", string.Empty, ReadOnly),
new SessionStateAliasEntry("ihy", "Invoke-History", string.Empty, ReadOnly),
new SessionStateAliasEntry("ii", "Invoke-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("ipmo", "Import-Module", string.Empty, ReadOnly),
new SessionStateAliasEntry("ipal", "Import-Alias", string.Empty, ReadOnly),
new SessionStateAliasEntry("ipcsv", "Import-Csv", string.Empty, ReadOnly),
new SessionStateAliasEntry("measure", "Measure-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("mi", "Move-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("mp", "Move-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("nal", "New-Alias", string.Empty, ReadOnly),
new SessionStateAliasEntry("ndr", "New-PSDrive", string.Empty, ReadOnly),
new SessionStateAliasEntry("ni", "New-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("nv", "New-Variable", string.Empty, ReadOnly),
new SessionStateAliasEntry("nmo", "New-Module", string.Empty, ReadOnly),
new SessionStateAliasEntry("oh", "Out-Host", string.Empty, ReadOnly),
new SessionStateAliasEntry("rbp", "Remove-PSBreakpoint", string.Empty, ReadOnly),
new SessionStateAliasEntry("rdr", "Remove-PSDrive", string.Empty, ReadOnly),
new SessionStateAliasEntry("ri", "Remove-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("rni", "Rename-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("rnp", "Rename-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("rp", "Remove-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("rmo", "Remove-Module", string.Empty, ReadOnly),
new SessionStateAliasEntry("rv", "Remove-Variable", string.Empty, ReadOnly),
new SessionStateAliasEntry("rvpa", "Resolve-Path", string.Empty, ReadOnly),
new SessionStateAliasEntry("sal", "Set-Alias", string.Empty, ReadOnly),
new SessionStateAliasEntry("sbp", "Set-PSBreakpoint", string.Empty, ReadOnly),
new SessionStateAliasEntry("select", "Select-Object", string.Empty, ReadOnly_AllScope),
new SessionStateAliasEntry("si", "Set-Item", string.Empty, ReadOnly),
new SessionStateAliasEntry("sl", "Set-Location", string.Empty, ReadOnly),
new SessionStateAliasEntry("sp", "Set-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("saps", "Start-Process", string.Empty, ReadOnly),
new SessionStateAliasEntry("spps", "Stop-Process", string.Empty, ReadOnly),
new SessionStateAliasEntry("sv", "Set-Variable", string.Empty, ReadOnly),
// Web cmdlets aliases
new SessionStateAliasEntry("irm", "Invoke-RestMethod", string.Empty, ReadOnly),
new SessionStateAliasEntry("iwr", "Invoke-WebRequest", string.Empty, ReadOnly),
// Porting note: #if !UNIX is used to disable aliases for cmdlets which conflict with Linux / macOS
#if !UNIX
// ac is a native command on macOS
new SessionStateAliasEntry("ac", "Add-Content", string.Empty, ReadOnly),
new SessionStateAliasEntry("compare", "Compare-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("cpp", "Copy-ItemProperty", string.Empty, ReadOnly),
new SessionStateAliasEntry("diff", "Compare-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("gsv", "Get-Service", string.Empty, ReadOnly),
new SessionStateAliasEntry("sleep", "Start-Sleep", string.Empty, ReadOnly),
new SessionStateAliasEntry("sort", "Sort-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("start", "Start-Process", string.Empty, ReadOnly),
new SessionStateAliasEntry("sasv", "Start-Service", string.Empty, ReadOnly),
new SessionStateAliasEntry("spsv", "Stop-Service", string.Empty, ReadOnly),
new SessionStateAliasEntry("tee", "Tee-Object", string.Empty, ReadOnly),
new SessionStateAliasEntry("write", "Write-Output", string.Empty, ReadOnly),
// These were transferred from the "transferred from the profile" section
new SessionStateAliasEntry("cat", "Get-Content"),
new SessionStateAliasEntry("cp", "Copy-Item", string.Empty, AllScope),
new SessionStateAliasEntry("ls", "Get-ChildItem"),
new SessionStateAliasEntry("man", "help"),
new SessionStateAliasEntry("mount", "New-PSDrive"),
new SessionStateAliasEntry("mv", "Move-Item"),
new SessionStateAliasEntry("ps", "Get-Process"),
new SessionStateAliasEntry("rm", "Remove-Item"),
new SessionStateAliasEntry("rmdir", "Remove-Item"),
new SessionStateAliasEntry("cnsn", "Connect-PSSession", string.Empty, ReadOnly),
new SessionStateAliasEntry("dnsn", "Disconnect-PSSession", string.Empty, ReadOnly),
#endif
// Bash built-ins we purposefully keep even if they override native commands
new SessionStateAliasEntry("cd", "Set-Location", string.Empty, AllScope),
new SessionStateAliasEntry("dir", "Get-ChildItem", string.Empty, AllScope),
new SessionStateAliasEntry("echo", "Write-Output", string.Empty, AllScope),
new SessionStateAliasEntry("fc", "Format-Custom", string.Empty, ReadOnly),
new SessionStateAliasEntry("kill", "Stop-Process"),
new SessionStateAliasEntry("pwd", "Get-Location"),
new SessionStateAliasEntry("type", "Get-Content"),
// Native commands we keep because the functions act correctly on Linux
new SessionStateAliasEntry("clear", "Clear-Host"),
// #if !CORECLR is used to disable aliases for cmdlets which are not available on OneCore or not appropriate for PSCore6 due to conflicts
#if !CORECLR
new SessionStateAliasEntry("gwmi", "Get-WmiObject", string.Empty, ReadOnly),
new SessionStateAliasEntry("iwmi", "Invoke-WMIMethod", string.Empty, ReadOnly),
new SessionStateAliasEntry("ogv", "Out-GridView", string.Empty, ReadOnly),
new SessionStateAliasEntry("ise", "powershell_ise.exe", string.Empty, ReadOnly),
new SessionStateAliasEntry("rwmi", "Remove-WMIObject", string.Empty, ReadOnly),
new SessionStateAliasEntry("sc", "Set-Content", string.Empty, ReadOnly),
new SessionStateAliasEntry("swmi", "Set-WMIInstance", string.Empty, ReadOnly),
new SessionStateAliasEntry("shcm", "Show-Command", string.Empty, ReadOnly),
new SessionStateAliasEntry("trcm", "Trace-Command", string.Empty, ReadOnly),
new SessionStateAliasEntry("lp", "Out-Printer"),
#endif
// Aliases transferred from the profile
new SessionStateAliasEntry("h", "Get-History"),
new SessionStateAliasEntry("history", "Get-History"),
new SessionStateAliasEntry("md", "mkdir", string.Empty, AllScope),
new SessionStateAliasEntry("popd", "Pop-Location", string.Empty, AllScope),
new SessionStateAliasEntry("pushd", "Push-Location", string.Empty, AllScope),
new SessionStateAliasEntry("r", "Invoke-History"),
new SessionStateAliasEntry("cls", "Clear-Host"),
new SessionStateAliasEntry("chdir", "Set-Location"),
new SessionStateAliasEntry("copy", "Copy-Item", string.Empty, AllScope),
new SessionStateAliasEntry("del", "Remove-Item", string.Empty, AllScope),
new SessionStateAliasEntry("erase", "Remove-Item"),
new SessionStateAliasEntry("move", "Move-Item", string.Empty, AllScope),
new SessionStateAliasEntry("rd", "Remove-Item"),
new SessionStateAliasEntry("ren", "Rename-Item"),
new SessionStateAliasEntry("set", "Set-Variable"),
new SessionStateAliasEntry("icm", "Invoke-Command"),
new SessionStateAliasEntry("clhy", "Clear-History", string.Empty, ReadOnly),
// Job Specific aliases
new SessionStateAliasEntry("gjb", "Get-Job"),
new SessionStateAliasEntry("rcjb", "Receive-Job"),
new SessionStateAliasEntry("rjb", "Remove-Job"),
new SessionStateAliasEntry("sajb", "Start-Job"),
new SessionStateAliasEntry("spjb", "Stop-Job"),
new SessionStateAliasEntry("wjb", "Wait-Job"),
#if !CORECLR
new SessionStateAliasEntry("sujb", "Suspend-Job"),
new SessionStateAliasEntry("rujb", "Resume-Job"),
// Remoting Cmdlets Specific aliases
new SessionStateAliasEntry("npssc", "New-PSSessionConfigurationFile", string.Empty, ReadOnly),
new SessionStateAliasEntry("ipsn", "Import-PSSession"),
new SessionStateAliasEntry("epsn", "Export-PSSession"),
#endif
new SessionStateAliasEntry("nsn", "New-PSSession"),
new SessionStateAliasEntry("gsn", "Get-PSSession"),
new SessionStateAliasEntry("rsn", "Remove-PSSession"),
new SessionStateAliasEntry("etsn", "Enter-PSSession"),
new SessionStateAliasEntry("rcsn", "Receive-PSSession", string.Empty, ReadOnly),
new SessionStateAliasEntry("exsn", "Exit-PSSession"),
// Win8: 121662/169179 Add "sls" alias for Select-String cmdlet
// - do not use AllScope - this causes errors in profiles that set this somewhat commonly used alias.
new SessionStateAliasEntry("sls", "Select-String"),
};
}
}
конечно, вышеуказанные псевдонимы могут быть изменены, но доступ к ним таким образом может быть более удобным/информативным в некоторых ситуациях.