V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
bddxg
V2EX  ›  PowerShell

请教 win11 powershell 设置别名的问题

  •  
  •   bddxg · 103 天前 · 813 次点击
    这是一个创建于 103 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我自己找到了一些设置别名的教程文章 比如 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 、函数、脚本文件或可运行程序的名称

    求大佬指教一下

    5 条回复    2024-01-15 10:30:50 +08:00
    Tumblr
        1
    Tumblr  
       103 天前   ❤️ 1
    貌似 PowerShell 里 alias 的值里不能有空格,像 OP 的需求这样子可以用函数:
    function pmsp { pnpm store prune }
    cxsz
        2
    cxsz  
       103 天前   ❤️ 1
    # 别名 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
        3
    bddxg  
    OP
       103 天前
    @Tumblr 大哥牛逼

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

    成功了
    Tumblr
        4
    Tumblr  
       103 天前   ❤️ 1
    @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
        5
    Rache1  
       103 天前   ❤️ 1
    你直接在 $profile 里面写个函数也可以

    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:33 · PVG 06:33 · LAX 15:33 · JFK 18:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.