请教 win11 powershell 设置别名的问题

115 天前
 bddxg

我自己找到了一些设置别名的教程文章 比如 https://segmentfault.com/a/1190000015928399 但是我目前遇到了一个难题, 可能是我的理解不够

我有个长命令 pnpm store prune, 我希望能用pmsp 来替代这个命令 我不知道该如何设置 我尝试过

Set-Alias -Name pmsp -Value "pnpm store prune"
Set-Alias pmsp "pnpm store prune"
Set-Alias pmsp pnpm store prune

以上都不行,要么直接打开终端就报错, 要么执行 pmsp 的时候提示无法将“pnpm store prune”项识别为 cmdlet 、函数、脚本文件或可运行程序的名称

求大佬指教一下

837 次点击
所在节点    PowerShell
5 条回复
Tumblr
115 天前
貌似 PowerShell 里 alias 的值里不能有空格,像 OP 的需求这样子可以用函数:
function pmsp { pnpm store prune }
cxsz
115 天前
# 别名 gcm 映射到 git commit -m
function Get-git-commit-m { git commit -m $args }
New-Alias -Name gcm -Value Get-git-commit-m -Force

# 别名 gst 映射到 git status
function Get-GitStatus { git status $args }
New-Alias -Name gst -Value Get-GitStatus -Force

# 别名 ga 映射到 git add
function Get-GitAdd { git add $args }
New-Alias -Name ga -Value Get-GitAdd -Force

这样写,放在$profile 文件里面
bddxg
115 天前
@Tumblr 大哥牛逼

# 设置别名
function SetPnpmStorePrune { pnpm store prune }
Set-Alias -Name pm -Value pnpm
Set-Alias -Name pmsp -Value SetPnpmStorePrune

成功了
Tumblr
115 天前
@bddxg #3 这就有点过于复杂了,直接 function pmsp { pnpm store prune } 就好了,不需要再设置 alias 了。。。

alias 的本意是,微软自己也知道他们的 cmdlets 又臭又长,所以对一些他们认为的常用 cmdlets 做了简化,比如 gc -> Get-Content, gci -> Get-ChildItem ,以及一些为了照顾其它用户的使用习惯,比如 ps -> Get-Process, wget -> Invoke-WebRequest 。
现在你自己去写 function ,直接用一个期望的简短函数名就可以了,没必要先写一个长的,再做 alias 。
当然啦,如果在遵循 PowerShell 的 Verb-Noun 的格式来写函数,然后再映射到 alias ,那当然是极好的。
Rache1
115 天前
你直接在 $profile 里面写个函数也可以

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1008646

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX