Windows PowerShell 设置命令别名永久生效

PowerShell Windows About 1,636 words

当前会话生效

Set-Alias -Name k -Value kubectl

设置永久生效

PowerShell 配置文件位置

文件不一定存在

$profile

$PsHome

$profile.AllUsersAllHosts

$profile.AllUsersCurrentHost

$profile.CurrentUserAllHosts

$profile.CurrentUserCurrentHost

输出

PS C:\Users\fendoudebb> $profile
C:\Users\fendoudebb\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS C:\Users\fendoudebb> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0
PS C:\Users\fendoudebb> $profile.AllUsersAllHosts
C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
PS C:\Users\fendoudebb> $profile.AllUsersCurrentHost
C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1
PS C:\Users\fendoudebb> $profile.CurrentUserAllHosts
C:\Users\fendoudebb\Documents\WindowsPowerShell\profile.ps1
PS C:\Users\fendoudebb> $profile.CurrentUserCurrentHost
C:\Users\fendoudebb\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

创建配置文件

PowerShell中输入如下命令:

if (!(Test-Path -Path $PROFILE)) {
  New-Item -ItemType File -Path $PROFILE -Force
}

设置别名

打开配置文件添加内容:

语法:

function 别名 { 原命令 @Args }

示例:

function k { kubectl @Args }

直接在命令行设置

echo "function k { kubectl @Args }" >> $profile

可能的错误

错误信息

File xxx\Microsoft.PowerShell_profile.ps1 cannot be loaded because running scripts is disabled on this system

错误原因

Windows系统为了防止恶意脚本自动执行,故默认不允许自动运行脚本。

解决方法

获取执行策略

Get-ExecutionPolicy

输出:如果是RemoteSigned,则不用再更改执行策略。

PS C:\Users\fendoudebb> Get-ExecutionPolicy
RemoteSigned

以管理员身份,在PowerShell中执行Set-ExecutionPolicy RemoteSigned,即可。

Set-ExecutionPolicy RemoteSigned

参考

https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_profiles

Views: 1,486 · Posted: 2022-08-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh