PowerShell最佳使用实践

偏向技术
/ 0 评论 / 119 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年07月05日,已超过683天没有更新,若内容或图片失效,请留言反馈。

PowerShell 是一种跨平台的任务自动化解决方案,由命令行 shell、脚本语言和配置管理框架组成。 PowerShell 在 Windows、Linux 和 macOS 上运行,这里主要介绍怎么使 PowerShell 在 Windows 下像 Bash 在 Linux 下一样好用。

准备

安装 Windows Terminal

应用商店安装(建议)

Windows Terminal:点此链接

Windows Terminal Preview:点此链接

Github 安装

进入 Release 页面,选择 Win 10 或者 Win 11 系统下载

包管理器安装(建议)

打开 PowerShell,输入 winget search "Microsoft.WindowsTerminal",结果如下所示:

❯ winget search "Microsoft.WindowsTerminal"
名称                     ID                                版本         源
-------------------------------------------------------------------------------
Windows Terminal         Microsoft.WindowsTerminal         1.13.11431.0 winget
Windows Terminal Preview Microsoft.WindowsTerminal.Preview 1.14.1432.0  winget
12345

执行安装命令 winget install --id=Microsoft.WindowsTerminal -e

Scoop 安装

powershell
scoop bucket add extras
scoop install windows-terminal
# update
scoop update windows-terminal
1234

升级 PowerShell

包管理器

powershell
winget install Microsoft.PowerShell
# or
winget upgrade Microsoft.PowerShell
123

MSI 安装

下载对应的 msi 包,进行安装

Windows terminal 配置

nerdfont 字体下载

Nerd Fonts 是一个使用大量字体图标来解决程序员在开发过程中缺少合适字体的问题的项目,进入 nerdfonts 下载页面,这里推荐 Caskaydia Cove Nerd Font,下载之后,解压缩安装

Windows terminal 设置

打开 Windows Terminal,进入设置

image-20220705184426273

打开 JSON 文件

image-20220705184540693

修改配置文件 settings.json

image-20220705185211405

从可视化设置页面进行修改

image-20220705185510513

配色方案选择

进入windowsterminalthemes,选择一个喜欢的 Theme,点击 Get theme 按钮,以 Dark+ 主题为例

image-20220705185755254

进入配置文件 settings.json,找到 schemes,将复制好的 json 内容复制到该位置下,记好对应的 name

image-20220705190113210

修改 colorScheme,即完成了主题更换

image-20220705190313833

PowerShell 配置

准备

确认当前 PowerShell 版本在 7.x 以上,如果当前显示的版本不是 7.x 以上,修改上文 Windows terminal 设置 中的默认配置文件过程

powershell
❯ $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.2.5
PSEdition                      Core
GitCommitId                    7.2.5
OS                             Microsoft Windows 10.0.25151
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
12345678910111213

安装 PowerShell 模块

powershell
# posh-git 是一个提供 Git/PowerShell 集成的 PowerShell 模块
Install-Module posh-git -Scope CurrentUser
# 适用于任何 shell 的提示主题引擎,美化作用
Install-Module oh-my-posh -Scope CurrentUser
# 一个提供快速注册 tab-completion 和添加别名的模块
Install-Module Register-Completion -Scope CurrentUser
123456

PowerShell 设置

打开配置文件,第一次可能不存在配置文件,执行下面命令,如果不存在,则创建,接着会在

powershell
if (!(Test-Path $profile)) {
    New-Item $profile -Force
}
notepad $profile
# 如果有使用 vscode,推荐通过 vscode 打开
code $profile
123456

进入打开的 $profile 文件,导入模块,这样会在每次启动 Terminal 前执行其中的命令

Import-Module posh-git
Import-Module oh-my-posh
Import-Module Register-Completion
123

其他设置

进入 ohmyposh 主题页面,选择一个主题,这里推荐 paradox

powershell
# 设置 oh-my-posh 主题
Set-PoshPrompt -Theme paradox
12

切换字符格式

powershell
chcp 936
1

PSReadLine 配置(非常有用)

powershell
# 设置预测文本来源为历史记录,(推荐)
Set-PSReadLineOption -PredictionSource History

# 每次回溯输入历史,光标定位于输入内容末尾
Set-PSReadLineOption -HistorySearchCursorMovesToEnd

# 设置 Tab 为菜单补全和 Intellisense,(推荐)
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete

# 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward

# 设置向下键为前向搜索历史纪录
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
1234567891011121314

设置 Alias,这里借助 Register-Completion,可以实现和 Bash 设置别名一样的体验,下面是一些示例:

powershell
Register-Alias ll ls
Register-Alias la ls
Register-Alias np notepad
Register-Alias swd "echo $pwd"
Register-Alias apps "cd ~/Projects"
Register-Alias i "cd ~/Projects/$($args[0])"
Register-Alias which Get-Command
Register-Alias ip "ipconfig /all | findstr '192'"
# 可以查看所有通过此方式注册的所有 Alias,除了纯粹的别名外(ll,la,np这种)
Register-Alias myAlias "Get-Command -CommandType Function -Name '*AliasFunction'"
12345678910

常用命令自动补全结合 Alias 使用,执行下面命令后,输入 nc <Tab>,如果有经常使用的命令,可以添加到下面,更多内容点击查看

powershell
# 下面命令请勿用双引号包裹
Register-Alias nc '"$args" | Invoke-Expression'
# 下面命令,仅做演示用,真实场景可用于 ssh 命令或者真正的常用命令
New-Completion nc @{
   'scoop update' = @{'#tooltip' = 'Update scoop'};
   'winget upgrade' = @{'#tooltip' = 'Upgrade winget'};
}
1234567

Winget 自动补全

powershell
# https://github.com/microsoft/winget-cli/blob/master/doc/Completion.md
Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock {
   param($wordToComplete, $commandAst, $cursorPosition)
   [Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()

   $word = $wordToComplete.Replace('"', '""')
   $ast = $commandAst.ToString().Replace('"', '""')
   winget complete --word="$word" --commandline "$ast" --position $cursorPosition | ForEach-Object {
      [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
   }
}
1234567891011

近期系统错误

powershell
function Get-ErrorEvent {
   param
   (
      # suggest today, yesterday, and last week:
      [ArgumentCompleter({
            $today = Get-Date -Format 'yyyy-MM-dd'
            $yesterday = (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')
            $lastWeek = (Get-Date).AddDays(-7).ToString('yyyy-MM-dd')

            # create the completions:
            [System.Management.Automation.CompletionResult]::new($today, "Today", "ParameterValue", "all errors after midnight")
            [System.Management.Automation.CompletionResult]::new($yesterday, "Yesterday", "ParameterValue", "all errors after yesterday")
            [System.Management.Automation.CompletionResult]::new($lastWeek, "Last Week", "ParameterValue", "all errors after last week")

         })]
      [DateTime]
      $After
   )

   # forward the parameter -After to Get-EventLog
   # if the user does not specify the parameter, all errors are returned:
   Get-EventLog -LogName System -EntryType Error @PSBoundParameters
}
1234567891011121314151617181920212223

总结

通过这几项设置,可以将 PowerShell 的体验拉到最好!!!

0

评论 (0)

取消