当前位置: 首页 > news >正文

PowerShell 终端环境自动化配置

介绍

在 Windows 上,PowerShell 是一个强大的终端和脚本语言环境。然而,默认配置可能并不适合高级用户,特别是习惯 Linux 终端的用户。因此,我们可以通过自动化脚本来一键配置 PowerShell,使其更加高效、美观,并增强生产力。

本教程将使用一个自动化安装脚本,在新设备上快速部署完整的 PowerShell 终端环境。


1️⃣ 自动化安装 PowerShell 终端环境

我们提供了一个 setup-powershell.ps1 脚本,能够自动完成以下任务:

安装必要的软件(使用 Winget & Scoop)

  • gsudo (提升管理员权限)
  • oh-my-posh (PowerShell 美化)
  • zoxide (智能目录跳转)
  • eza(更现代化的 ls
  • ripgrep(更快的 grep

创建 PowerShell 配置目录$HOME\.powershell
创建所有配置文件(主题、历史记录、快捷键、别名等)
确保 PowerShell 使用 UTF-8 作为默认编码
配置 $PROFILE 自动加载所有配置文件

📥 创建脚本文件 & 运行

如果你已经创建了 setup-powershell.ps1,并且添加了内容,那么直接运行它即可:

& "C:\Users\你的用户名\Documents\setup-powershell.ps1"

2️⃣ 自动化安装脚本

以下是 setup-powershell.ps1 的完整代码:

# 配置模块的文件路径
$PSConfigPath = "$HOME\.powershell"

Write-Host "`n===== 开始备份并更新 PowerShell 配置 =====`n" -ForegroundColor Cyan
# 备份并重置 $PROFILE 文件
if (Test-Path $PROFILE) {
    Move-Item -Path $PROFILE -Destination "$PROFILE.bak" -Force
    Write-Host "📝 $PROFILE 已备份到 $PROFILE.bak"
}
New-Item -ItemType File -Path $PROFILE -Force | Out-Null
Write-Host "✅ 已创建新的 PowerShell 配置文件: $PROFILE"

# 备份旧的 PowerShell 模块配置目录
if (Test-Path $PSConfigPath) {
    $backupPath = "$HOME\.powershell_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
    Move-Item -Path $PSConfigPath -Destination $backupPath -Force
    Write-Host "📂 旧的配置已备份到: $backupPath"
}

# PowerShell 配置自动化安装脚本
Write-Host "`n===== 开始配置 PowerShell 环境 =====`n" -ForegroundColor Cyan

# 创建 PowerShell 配置目录(如果不存在则创建)
if (!(Test-Path $PSConfigPath)) {
    New-Item -ItemType Directory -Path $PSConfigPath -Force | Out-Null
    Write-Host "✅ 已创建 PowerShell 配置目录: $PSConfigPath"
} else {
    Write-Host "📂 PowerShell 配置目录已存在,跳过创建"
}

# 设置 PowerShell 的输出编码为 UTF-8
# [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 设定 PowerShell UTF-8 编码
# $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
# $PSDefaultParameterValues['Get-Content:Encoding'] = 'utf8'
# $PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8'

# 自动安装所需软件(Winget)
Write-Host "`n===== 检查并安装 Winget 软件 =====" -ForegroundColor Green
$wingetPackages = @(
    @{ Name = "gsudo"; Package = "gerardog.gsudo" },
    @{ Name = "Oh My Posh"; Package = "JanDeDobbeleer.OhMyPosh" },
    @{ Name = "zoxide"; Package = "ajeetdsouza.zoxide" }
)

foreach ($software in $wingetPackages) {
    if (!(Get-Command $software.Name -ErrorAction SilentlyContinue)) {
        Write-Host "📦 安装 $($software.Package)..."
        winget install --id=$($software.Package) --silent --accept-source-agreements --accept-package-agreements
    } else {
        Write-Host "✅ $($software.Name) 已安装,跳过"
    }
}

# 安装 Scoop(如果未安装)
Write-Host "`n===== 检查并安装 Scoop 软件 =====" -ForegroundColor Green
if (!(Get-Command scoop -ErrorAction SilentlyContinue)) {
    Write-Host "📦 Scoop 未安装,正在安装..."
    Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression
}

# 添加 Scoop 的 main 仓库(如果未添加)
if (-not (scoop bucket list | Select-String "main")) {
    scoop bucket add main
}

# Scoop 软件列表
$scoopPackages = @("eza", "ripgrep")
foreach ($pkg in $scoopPackages) {
    if (!(Get-Command $pkg -ErrorAction SilentlyContinue)) {
        Write-Host "📦 安装 $pkg..."
        scoop install $pkg
    } else {
        Write-Host "✅ $pkg 已安装,跳过"
    }
}

Write-Host "`n===== 开始写入 PowerShell 配置文件 =====`n" -ForegroundColor Cyan
# 写入 $PROFILE,确保终端启动时自动加载配置
$ProfileConfig = @'
# 设置 PowerShell 的输出编码为 UTF-8
# [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 设置 Windows 控制台的默认代码页为 UTF-8
# chcp 65001 | Out-Null

# 以 UTF-8 读取并加载所有文件
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['Get-Content:Encoding'] = 'utf8'
$PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8'

# .bashrc 风格的自动加载
# 需要的配置文件列表
$files = @(
    "theme.ps1",        # 主题相关配置
    "history.ps1",      # 历史记录 & 语法高亮
    "keybindings.ps1",  # 快捷键 & 编辑模式
    "tools.ps1",        # 终端增强工具(zoxide 等)
    "aliases.ps1",      # 别名配置
    "functions.ps1",    # 自定义函数
    "devtools.ps1"      # 开发工具别名
    "extra.ps1"         # 其他扩展配置(可选)
)

# 确保 $HOME\.powershell 目录存在
if (!(Test-Path "$HOME\.powershell")) {
    New-Item -ItemType Directory -Path "$HOME\.powershell" -Force
    Write-Host "Created directory: $profileDir"
}

# 遍历创建文件(如果不存在)
foreach ($file in $files) {
    $filePath = "$HOME\.powershell\$file"
    if (!(Test-Path $filePath)) {
        New-Item -ItemType File -Path $filePath -Force | Out-Null
        Write-Host "Created: $filePath"
    } else {
        Write-Host "Exists: $filePath (skipped)"
    }
}

# 自动加载 .powershell 目录下的配置文件
foreach ($file in $files) {
    $filePath = "$HOME\.powershell\$file"
    if (Test-Path $filePath) {
        . $filePath
    }
}

Write-Host "PowerShell configuration loaded successfully!"
Write-Host "Current output encoding: $([Console]::OutputEncoding.EncodingName)"
'@

# 确保 $PROFILE 存在并写入内容
Set-Content -Path $PROFILE -Value $ProfileConfig

# 定义模块配置文件及内容
$files = @{
    "aliases.ps1" = @'
# 模拟 Linux 常用命令
Set-Alias ll Get-ChildItem
Set-Alias touch New-Item
Set-Alias grep Select-String
Set-Alias which Get-Command
'@;

    "functions.ps1" = @'
# 在线命令解析
function explain {
    $cmd = $args -join "+"
    Invoke-RestMethod -Uri "https://cheat.sh/$cmd" -UseBasicParsing
}

# 自动升级所有软件
function UpdateAll {
    Write-Host "Updating Windows software using winget..."
    winget upgrade --all --silent
}

# 快速编辑配置文件
function edit-profile { notepad $PROFILE }

# 清空控制台和历史记录
function cls! {
    Clear-Host
    [System.Console]::Clear()
}

# 快速查看网络信息
function myip { Invoke-RestMethod ifconfig.me }

# 快速进入常用目录
function desk { Set-Location "$HOME\Desktop" }
function docs { Set-Location "$HOME\Documents" }
function proj { Set-Location "$HOME\Documents\Projects" }
function scripts { Set-Location "$HOME\Documents\Scripts" }
function downloads { Set-Location "$HOME\Downloads" }

# Winget 安装和搜索软件 
function install { param($pkg) winget install $pkg }
function searchpkg { param($name) winget search $name }

# 查看系统信息
function sysinfo {
    Get-ComputerInfo | Select-Object OsName, OsArchitecture, CsTotalPhysicalMemory, WindowsProductName, OsVersion
}

# 检查网络连通性
function pingtest {
    Test-Connection -ComputerName 8.8.8.8 -Count 4
}

# 清理回收站
function empty-trash {
    Clear-RecycleBin -Force
}

# 快速测试端口是否开放
function test-port {
    param (
        [string]$host,
        [int]$port
    )
    Test-NetConnection -ComputerName $host -Port $port
}

# 搜索文件内容
function find-text {
    param($text, $path = ".")
    Get-ChildItem -Recurse -File -Path $path | Select-String -Pattern $text
}
'@;

    "history.ps1" = @'
# 启用语法高亮(自定义颜色)
Set-PSReadLineOption -Colors @{ "Command" = "DarkYellow" }

# 启用历史预测、Tab 补全 & 搜索优化
# InlineView和ListView二选一。如果喜欢像 GitHub Copilot 的灰色提示,建议使用 InlineView;如果喜欢候选列表样式,用 ListView。
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineOption -HistorySearchCursorMovesToEnd

# 持久化历史记录(自动保存)
Set-PSReadLineOption -HistorySaveStyle SaveIncrementally

# 增加历史记录条数 & 避免重复项
# Set-PSReadLineOption -MaximumHistoryCount 30
# Set-PSReadLineOption -HistoryNoDuplicates
'@;

    "keybindings.ps1" = @'
# 设置编辑模式为 Emacs(更常见的按键逻辑)
Set-PSReadLineOption -EditMode Emacs
'@;

    "theme.ps1" = @'
# 设置主题
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/powerlevel10k_rainbow.omp.json" | Invoke-Expression
'@;

    "tools.ps1" = @'
# 配置 zoxide (更强大的 cd 命令)
Invoke-Expression (& { (zoxide init powershell) -join "`n" })
'@;

    "extra.ps1" = @'
# 用户扩展文件,可自定义额外的别名和函数

Set-Alias sudo gsudo
'@;

    "devtools.ps1" = @'
'@
}

# 遍历写入每个配置文件
foreach ($file in $files.Keys) {
    $filePath = "$PSConfigPath\$file"
    
    # 确保文件目录存在
    if (!(Test-Path $PSConfigPath)) {
        New-Item -ItemType Directory -Path $PSConfigPath -Force | Out-Null
    }

    # 写入文件(覆盖旧内容,确保完整写入)
    Set-Content -Path $filePath -Value $files[$file]
    Write-Host "✅ 配置文件写入成功: $filePath"
}

Write-Host "✅ 所有 PowerShell 配置文件已完成!"
Write-Host "✅ 请运行 .\$PROFILE 使其生效!!!"

总结

通过 setup-powershell.ps1,你可以一键配置 PowerShell 终端,自动安装软件、创建配置文件,并优化编码和历史记录。下一步,我们将介绍具体的配置文件内容,敬请期待!

相关文章:

  • 【大语言模型_8】vllm启动的模型通过fastapi封装增加api-key验证
  • 物种分化在进化拓扑中的作用
  • 《深度学习》—— 模型部署
  • JAVA泛型的作用
  • RAGFlow爬虫组件使用及ragflow vs dify 组件设计对比
  • 深度学习篇---深度学习中的范数
  • 软考中级网络工程师第八章网络安全
  • 【react】工程项目中的通过自定义Hook进行路由设计以及路由鉴权
  • Python Django入门(创建应用程序)
  • Mysql表的简单操作
  • 深度解析学术论文成果评估(Artifact Evaluation):从历史到现状
  • 【React】基于自定义Hook提取公共逻辑
  • MySQL:float,decimal(1)
  • Python学习第二十一天
  • 风暴潮、潮汐潮流模拟:ROMS模型如何精准预测海洋现象?
  • 云盘搭建笔记
  • 《Python实战进阶》No42: 多线程与多进程编程详解(下)
  • 四种事件类型
  • 自适应柔顺性策略:扩散引导控制中学习近似的柔顺
  • Python中的null是什么?
  • 前四个月社会融资规模增量累计为16.34万亿元,比上年同期多3.61万亿元
  • 我的科学观|梅彦昌:科技创新关键在于能否跑得快,而不是有没有钱
  • 专访|茸主:杀回UFC,只为给自己一个交代
  • 夜读丨取稿费的乐趣
  • 冷冰川谈黑白
  • 体验中国传统文化、采购非遗文创,波兰游客走进上海市群艺馆