Windows-PowerShell设置别名

  1. 需求
  2. 步骤
    1. 1. 新建配置文件
    2. 2. 修改配置文件
    3. 3. 使配置生效
  3. 参考

需求

输入一长串命令非常繁琐,考虑简化命令输入,或者起别名。效果同 Linux 的 alias 设置别名。

步骤

1. 新建配置文件

查看配置文件位置

> Get-Variable Profile

Name                           Value
----                           -----
PROFILE                        C:\Users\ZJ\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

查看配置文件是否存在

> Test-Path $profile
True

不存在则创建

> New-Item -Type file -Force $profile

    Directory: C:\Users\ZJ\Documents\PowerShell

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2023/6/14    17:24              0 Microsoft.PowerShell_profile.ps1

2. 修改配置文件

把设置别名的命令放置在配置文件中,可以使修改永久生效

function Hexo-New { hexo new post }
function Hexo-Server { hexo clean && hexo g && hexo s --debug }
function Hexo-Deploy-Push { hexo clean && hexo g && hexo d && git add . && git commit -m "update" && git push }

Set-Alias hn Hexo-New
Set-Alias hs Hexo-Server
Set-Alias hdp Hexo-Deploy-Push

注意,只有带参数的命令才需要函数。已注册命令(包括绝对路径)直接 Set-Alias。支持引号。

3. 使配置生效

查看 PowerShell 默认执行策略

> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined

修改 PowerShell 默认执行策略,默认在启动的时候,会以 Restricted 模式运行,此时不允许执行任何脚本

> Set-Executionpolicy Remotesigned

重启 PowerShell

参考


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 470501267@qq.com