[小技巧] Windows - Powershell配置优化+allow function wgs → winget search
date
Mar 1, 2024
slug
tip-windows-powershell-function
status
Published
summary
小技巧
tags
tip
type
Post
URL
PowerShell
# if $PROFILE doesn't exist
New-Item -Path $PROFILE -Type File -Force
# 管理员身份
Install-Module -Name PSReadLine
vim $PROFILE
# --------------------------------------
Set-PSReadlineKeyHandler -Chord Tab -Function MenuComplete
Set-PSReadLineOption -EditMode Vi
# if not using vi, then
# Set-PSReadlineKeyHandler -Chord Ctrl+b,Ctrl+B -Function DeleteLine
# oh-my-posh
oh-my-posh init pwsh | Invoke-Expression
oh-my-posh init pwsh --config 'C:\Users\hone\AppData\Local\Programs\oh-my-posh\themes\wholespace.omp.json' | Invoke-Expression
# Set-Alias 只能给不含参数的命令设置别名
Set-alias 's' 'Select-Object'
#Set-alias 'IP' 'Get-IPInfo.ps1'
#Set-alias 'QN' 'C:\tools\qshell.exe'
# functions
# @args = 所有参数
function wgs { winget search $args[0] }
function wgi { winget install $args[0] }
# choco auto-completion
# Import the Chocolatey Profile that contains the necessary code to enable
# tab-completions to function for `choco`.
# Be aware that if you are missing these lines from your profile, tab completion
# for `choco` will not function.
# See https://ch0.co/tab-completion for details.
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
# winget auto-completion
Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()
$Local:word = $wordToComplete.Replace('"', '""')
$Local:ast = $commandAst.ToString().Replace('"', '""')
winget complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
# --------------------------------------
# use the profile
. $PROFILE
# change permission if error
# start a new shell as Admin
start-process PowerShell -verb runas
set-executionpolicy remotesigned
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned