晨枫u盘pe制作工具,让装系统变得更简单!

晨枫u盘pe系统

Windows PowerShell实用命令与自动化脚本大全:系统维护高效利器(2026版)

更新时间:2026-06-25 来源:晨枫U盘 阅读:1000次

一、PowerShell基础入门

1.1 什么是PowerShell

PowerShell是微软开发的跨平台任务自动化和配置管理框架,由命令行shell和脚本语言组成。相比传统的CMD命令提示符,PowerShell具有以下优势:

  • 基于.NET框架:可以访问系统底层API
  • 强大的管道功能:命令之间可以灵活传递数据
  • 面向对象:操作的是对象而非纯文本
  • 丰富的Cmdlet:内置数百个专用命令
  • 脚本自动化:支持编写复杂的自动化脚本

1.2 启动PowerShell

方法一:搜索启动

  1. 按Win键,搜索"PowerShell"
  2. 选择"Windows PowerShell"或"Windows PowerShell(管理员)"

方法二:快捷方式

  • Win + X → 选择"Windows PowerShell"或"终端"
  • Win + R → 输入powershell回车

方法三:在文件资源管理器中

  • 在文件夹地址栏输入powershell回车
  • 在当前文件夹打开PowerShell

方法四:右键菜单

  • 在文件夹空白处Shift+右键 → "在此处打开PowerShell窗口"

1.3 PowerShell基本语法

命令结构(Cmdlet命名规则):

动词-名词

例如:

  • Get-Process:获取进程列表
  • Set-Location:设置当前目录
  • New-Item:创建新项目

常用动词:

  • Get:获取信息
  • Set:设置配置
  • New:创建新项目
  • Remove:删除项目
  • Start:启动服务/进程
  • Stop:停止服务/进程

获取帮助:

# 查看所有命令
Get-Command

# 查看特定命令的帮助
Get-Help Get-Process

# 查看命令的详细帮助
Get-Help Get-Process -Detailed

# 查看命令的示例
Get-Help Get-Process -Examples

# 更新帮助文档
Update-Help

二、系统信息查询

2.1 计算机基本信息

# 计算机名称和基本信息
Get-ComputerInfo | Select-Object CsName, WindowsProductName, WindowsVersion, OsArchitecture

# 操作系统详细信息
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber, InstallDate

# 系统启动时间
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime

2.2 硬件信息查询

# CPU信息
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors, MaxClockSpeed

# 内存信息
Get-CimInstance Win32_PhysicalMemory | Select-Object Manufacturer, Capacity, Speed, ConfiguredClockSpeed

# 总内存和可用内存
$os = Get-CimInstance Win32_OperatingSystem
[PSCustomObject]@{
    TotalMemory = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
    FreeMemory = [math]::Round($os.FreePhysicalMemory / 1MB, 2)
    UsedMemory = [math]::Round(($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / 1MB, 2)
}

# 硬盘信息
Get-CimInstance Win32_DiskDrive | Select-Object Model, Size, InterfaceType, MediaType

# 显卡信息
Get-CimInstance Win32_VideoController | Select-Object Name, DriverVersion, AdapterRAM, VideoProcessor

2.3 网络信息查询

# IP地址信息
Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*"} | Select-Object InterfaceAlias, IPAddress, PrefixLength

# DNS服务器
Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object InterfaceAlias, ServerAddresses

# 网络适配器状态
Get-NetAdapter | Select-Object Name, Status, LinkSpeed, MacAddress

# 路由表
Get-NetRoute | Select-Object DestinationPrefix, NextHop, RouteMetric | Format-Table -AutoSize

2.4 软件安装信息

# 已安装的程序
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | 
    Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | 
    Where-Object {$_.DisplayName} | 
    Sort-Object DisplayName | 
    Format-Table -AutoSize

# 已安装的Windows更新
Get-HotFix | Select-Object HotFixID, Description, InstalledOn | Sort-Object InstalledDate -Descending | Select-Object -First 20

# Windows功能
Get-WindowsOptionalFeature -Online | Where-Object {$_.State -eq "Enabled"} | Select-Object FeatureName

三、系统管理实用命令

3.1 进程管理

# 查看所有进程
Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Name, Id, CPU, WorkingSet64

# 查找特定进程
Get-Process -Name chrome

# 停止进程
Stop-Process -Name notepad -Force

# 按CPU使用率排序
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

# 按内存使用排序
Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,2)}}

3.2 服务管理

# 查看所有运行中的服务
Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object Name, DisplayName, Status

# 查看特定服务
Get-Service -Name wuauserv

# 启动服务
Start-Service -Name wuauserv

# 停止服务
Stop-Service -Name wuauserv -Force

# 重启服务
Restart-Service -Name wuauserv

# 设置服务启动类型
Set-Service -Name wuauserv -StartupType Automatic

# 查看禁用状态的服务
Get-Service | Where-Object {$_.StartType -eq "Disabled"} | Select-Object Name, DisplayName

3.3 磁盘管理

# 查看磁盘分区
Get-Disk | Select-Object Number, FriendlyName, Size, PartitionStyle

# 查看卷信息
Get-Volume | Select-Object DriveLetter, FileSystemLabel, FileSystem, @{N='Size(GB)';E={[math]::Round($_.Size/1GB,2)}}, @{N='Free(GB)';E={[math]::Round($_.SizeRemaining/1GB,2)}}

# 清理临时文件
Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue

# 查看大文件
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | 
    Where-Object {$_.Length -gt 1GB} | 
    Sort-Object Length -Descending | 
    Select-Object FullName, @{N='Size(GB)';E={[math]::Round($_.Length/1GB,2)}} | 
    Select-Object -First 20

3.4 用户和权限管理

# 查看本地用户
Get-LocalUser | Select-Object Name, Enabled, LastLogon, Description

# 创建新用户
New-LocalUser -Name "NewUser" -Password (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -FullName "New User" -Description "New local user"

# 将用户添加到管理员组
Add-LocalGroupMember -Group "Administrators" -Member "NewUser"

# 查看用户所属组
Get-LocalUser | Where-Object {$_.Name -eq $env:USERNAME} | Select-Object Name, @{N='Groups';E={(Get-LocalGroup | Where-Object {(Get-LocalGroupMember $_.Name).Name -contains $env:USERNAME}).Name -join ', '}}

四、网络诊断与管理

4.1 网络连通性测试

# Ping测试
Test-Connection -ComputerName www.baidu.com -Count 4

# 批量Ping多个地址
$hosts = @("www.baidu.com", "www.qq.com", "www.taobao.com")
foreach ($host_name in $hosts) {
    $result = Test-Connection -ComputerName $host_name -Count 1 -Quiet
    Write-Host "$host_name : $(if($result){'可达'}else{'不可达'})"
}

# 端口测试
Test-NetConnection -ComputerName www.baidu.com -Port 443

# 跟踪路由
Test-Connection -ComputerName www.baidu.com -Traceroute

4.2 DNS管理

# 查看DNS缓存
Get-DnsClientCache | Select-Object Entry, Name, Data, TimeToLive

# 清除DNS缓存
Clear-DnsClientCache

# 设置DNS服务器
Set-DnsClientServerAddress -InterfaceAlias "以太网" -ServerAddresses ("223.5.5.5", "119.29.29.29")

# 刷新DNS注册
Register-DnsClient

4.3 防火墙管理

# 查看防火墙配置文件状态
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction

# 查看防火墙规则
Get-NetFirewallRule | Where-Object {$_.Enabled -eq "True"} | Select-Object DisplayName, Direction, Action | Select-Object -First 20

# 添加防火墙规则(允许程序)
New-NetFirewallRule -DisplayName "Allow Notepad" -Direction Inbound -Program "C:\Windows\notepad.exe" -Action Allow

# 删除防火墙规则
Remove-NetFirewallRule -DisplayName "Allow Notepad"

# 启用/禁用防火墙
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

4.4 网络共享管理

# 查看共享文件夹
Get-SmbShare | Select-Object Name, Path, Description

# 创建共享文件夹
New-SmbShare -Name "TestShare" -Path "C:\TestShare" -FullAccess "Everyone"

# 删除共享
Remove-SmbShare -Name "TestShare" -Force

# 查看SMB连接
Get-SmbConnection | Select-Object ServerName, ShareName, UserName

五、文件批量处理

5.1 文件搜索与筛选

# 查找特定类型的文件
Get-ChildItem -Path C:\Users -Recurse -Filter "*.pdf" -ErrorAction SilentlyContinue | Select-Object FullName, Length, LastWriteTime

# 查找最近修改的文件
Get-ChildItem -Path C:\Users -Recurse -File -ErrorAction SilentlyContinue | 
    Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} | 
    Select-Object FullName, LastWriteTime | 
    Sort-Object LastWriteTime -Descending

# 查找大文件
Get-ChildItem -Path D:\ -Recurse -File -ErrorAction SilentlyContinue | 
    Where-Object {$_.Length -gt 100MB} | 
    Sort-Object Length -Descending | 
    Select-Object FullName, @{N='Size(MB)';E={[math]::Round($_.Length/1MB,2)}}

5.2 文件批量重命名

# 批量添加前缀
Get-ChildItem -Path "C:\Photos" -Filter "*.jpg" | Rename-Item -NewName {"Vacation_" + $_.Name}

# 批量修改扩展名
Get-ChildItem -Path "C:\Documents" -Filter "*.txt" | Rename-Item -NewName {$_.BaseName + ".md"}

# 按日期重命名
Get-ChildItem -Path "C:\Photos" -Filter "*.jpg" | ForEach-Object {
    $date = $_.CreationTime.ToString("yyyyMMdd")
    Rename-Item $_.FullName -NewName "$date`_$($_.Name)"
}

# 批量替换文件名中的字符
Get-ChildItem -Path "C:\Files" | Where-Object {$_.Name -like "*old*"} | Rename-Item -NewName {$_.Name -replace "old","new"}

5.3 文件批量复制与移动

# 批量复制特定类型文件
Get-ChildItem -Path "C:\Source" -Recurse -Filter "*.docx" | Copy-Item -Destination "D:\Backup\Documents"

# 按日期筛选并复制
$cutoff = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\Projects" -Recurse -File | 
    Where-Object {$_.LastWriteTime -gt $cutoff} | 
    Copy-Item -Destination "D:\RecentBackup"

# 批量移动文件
Get-ChildItem -Path "C:\Downloads" -Filter "*.zip" | Move-Item -Destination "D:\Archives"

# 创建目录结构并复制
$folders = @("Documents", "Pictures", "Videos")
foreach ($folder in $folders) {
    New-Item -Path "D:\Backup\$folder" -ItemType Directory -Force
    Copy-Item -Path "$env:USERPROFILE\$folder\*" -Destination "D:\Backup\$folder" -Recurse -Force
}

5.4 文件内容处理

# 读取文件内容
Get-Content -Path "C:\config.txt"

# 读取文件最后10行
Get-Content -Path "C:\log.txt" -Tail 10

# 搜索文件内容
Select-String -Path "C:\logs\*.log" -Pattern "ERROR" | Select-Object FileName, LineNumber, Line

# 批量替换文件内容
Get-ChildItem -Path "C:\Config" -Filter "*.ini" | ForEach-Object {
    (Get-Content $_.FullName) -replace "old_value", "new_value" | Set-Content $_.FullName
}

# 合并多个文件
Get-Content -Path "C:\Logs\*.log" | Set-Content -Path "C:\Logs\merged.log"

六、注册表操作

6.1 注册表读取

# 读取注册表值
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" | Select-Object ProductName, CurrentBuild, DisplayVersion

# 列出注册表键下的所有值
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"

# 列出子键
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach-Object {
    Get-ItemProperty $_.PSPath
} | Where-Object {$_.DisplayName} | Select-Object DisplayName, DisplayVersion | Sort-Object DisplayName

6.2 注册表修改

# 设置注册表值
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Hidden" -Value 1

# 创建新的注册表键
New-Item -Path "HKCU:\Software\MyApp" -Force

# 创建新的注册表值
New-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting1" -Value "Value1" -PropertyType String

# 删除注册表值
Remove-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting1"

# 删除注册表键
Remove-Item -Path "HKCU:\Software\MyApp" -Recurse -Force

6.3 注册表备份与恢复

# 导出注册表键
reg export "HKCU\Software\MyApp" "C:\Backup\MyApp.reg" /y

# 导入注册表文件
reg import "C:\Backup\MyApp.reg"

# 使用PowerShell备份注册表
$regPath = "HKCU:\Software\MyApp"
$backupPath = "C:\Backup\MyApp_$(Get-Date -Format 'yyyyMMdd').reg"
reg export $regPath.Replace(':','') $backupPath /y

七、自动化脚本示例

7.1 系统信息收集脚本

# 收集系统信息并导出到文件
$report = @"
===== 系统信息报告 =====
生成时间: $(Get-Date)
计算机名: $env:COMPUTERNAME
用户名: $env:USERNAME

===== 操作系统 =====
$(Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber | Format-List | Out-String)

===== CPU信息 =====
$(Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, MaxClockSpeed | Format-List | Out-String)

===== 内存信息 =====
总内存: $([math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory/1GB,2)) GB

===== 磁盘信息 =====
$(Get-Volume | Where-Object {$_.DriveLetter} | Select-Object DriveLetter, FileSystemLabel, @{N='Size(GB)';E={[math]::Round($_.Size/1GB,2)}}, @{N='Free(GB)';E={[math]::Round($_.SizeRemaining/1GB,2)}} | Format-Table | Out-String)

===== 网络适配器 =====
$(Get-NetAdapter | Select-Object Name, Status, LinkSpeed | Format-Table | Out-String)
"@

$report | Out-File -FilePath "C:\SystemReport_$(Get-Date -Format 'yyyyMMdd').txt" -Encoding UTF8
Write-Host "报告已生成" -ForegroundColor Green

7.2 系统清理脚本

# 系统临时文件清理
Write-Host "开始系统清理..." -ForegroundColor Cyan

# 清理用户临时文件
$tempPath = $env:TEMP
$tempFiles = Get-ChildItem -Path $tempPath -Recurse -Force -ErrorAction SilentlyContinue
$beforeSize = ($tempFiles | Measure-Object -Property Length -Sum).Sum
Remove-Item -Path "$tempPath\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "用户临时文件已清理" -ForegroundColor Green

# 清理Windows临时文件
$winTemp = "C:\Windows\Temp"
Remove-Item -Path "$winTemp\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Windows临时文件已清理" -ForegroundColor Green

# 清理回收站
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
Write-Host "回收站已清空" -ForegroundColor Green

# 清理Windows更新缓存
Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\Windows\SoftwareDistribution\Download\*" -Recurse -Force -ErrorAction SilentlyContinue
Start-Service -Name wuauserv -ErrorAction SilentlyContinue
Write-Host "Windows更新缓存已清理" -ForegroundColor Green

# 清理DNS缓存
Clear-DnsClientCache
Write-Host "DNS缓存已清理" -ForegroundColor Green

Write-Host "系统清理完成!" -ForegroundColor Green

7.3 批量软件安装脚本

# 使用winget批量安装软件
$apps = @(
    "Google.Chrome",
    "7zip.7zip",
    "VideoLAN.VLC",
    "Notepad++.Notepad++",
    "Microsoft.PowerToys"
)

foreach ($app in $apps) {
    Write-Host "正在安装 $app ..." -ForegroundColor Yellow
    winget install --id $app --accept-source-agreements --accept-package-agreements
    Write-Host "$app 安装完成" -ForegroundColor Green
}

Write-Host "所有软件安装完成!" -ForegroundColor Cyan

7.4 网络诊断脚本

# 网络诊断脚本
Write-Host "===== 网络诊断报告 =====" -ForegroundColor Cyan
Write-Host "时间: $(Get-Date)" -ForegroundColor Gray

# 检查网络适配器
Write-Host "`n[1] 网络适配器状态:" -ForegroundColor Yellow
Get-NetAdapter | Where-Object {$_.Status -eq "Up"} | Select-Object Name, InterfaceDescription, LinkSpeed | Format-Table

# 检查IP配置
Write-Host "[2] IP配置:" -ForegroundColor Yellow
Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*"} | Select-Object InterfaceAlias, IPAddress, PrefixLength | Format-Table

# 测试网关连通性
$gateway = (Get-NetRoute -DestinationPrefix "0.0.0.0/0").NextHop
Write-Host "[3] 网关连通性 ($gateway):" -ForegroundColor Yellow
$ping = Test-Connection -ComputerName $gateway -Count 2 -Quiet
if ($ping) { Write-Host "  网关可达" -ForegroundColor Green } else { Write-Host "  网关不可达" -ForegroundColor Red }

# 测试DNS解析
Write-Host "[4] DNS解析测试:" -ForegroundColor Yellow
try {
    Resolve-DnsName -Name "www.baidu.com" -Type A -ErrorAction Stop | Select-Object Name, IPAddress | Format-Table
    Write-Host "  DNS解析正常" -ForegroundColor Green
} catch {
    Write-Host "  DNS解析失败" -ForegroundColor Red
}

# 测试外网连通性
Write-Host "[5] 外网连通性:" -ForegroundColor Yellow
$internet = Test-Connection -ComputerName "www.baidu.com" -Count 2 -Quiet
if ($internet) { Write-Host "  可以访问互联网" -ForegroundColor Green } else { Write-Host "  无法访问互联网" -ForegroundColor Red }

八、PowerShell在PE环境中的应用

8.1 PE环境下的PowerShell

晨枫PE工具箱支持PowerShell运行环境,可以在PE中执行以下操作:

离线系统信息查看:

# 查看离线系统的注册表
$offlineHive = "C:\Windows\System32\config\SOFTWARE"
reg load "HKLM\OfflineSoftware" $offlineHive
Get-ItemProperty "HKLM:\OfflineSoftware\Microsoft\Windows NT\CurrentVersion" | Select-Object ProductName, CurrentBuild
reg unload "HKLM\OfflineSoftware"

离线密码管理:

# 查看离线系统的用户列表
$samPath = "C:\Windows\System32\config\SAM"
# 使用chntpw等工具配合PowerShell脚本

离线驱动管理:

# 查看离线系统的驱动
dism /image:C:\ /get-drivers /format:table

8.2 配合晨枫PE工具箱

PowerShell可以与晨枫PE工具箱中的工具配合使用:

  • 自动化部署:编写脚本批量安装系统和软件
  • 数据备份:自动化备份重要文件到外部存储
  • 系统修复:编写脚本自动修复常见系统问题
  • 硬件检测:调用PE内置工具进行硬件诊断

九、常见问题与技巧

9.1 执行策略问题

问题:无法运行脚本,提示"无法加载文件,因为在此系统上禁止运行脚本"

解决:

# 查看当前执行策略
Get-ExecutionPolicy

# 设置执行策略(需要管理员权限)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

# 临时绕过执行策略运行脚本
powershell -ExecutionPolicy Bypass -File "C:\script.ps1"

9.2 权限问题

问题:命令执行失败,提示"拒绝访问"

解决:

# 以管理员身份运行PowerShell
Start-Process powershell -Verb RunAs

# 在脚本中检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Warning "请以管理员身份运行此脚本"
    break
}

9.3 编码问题

问题:脚本中的中文显示乱码

解决:

# 保存脚本时使用UTF-8 with BOM编码
# 或在脚本开头添加
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

9.4 实用技巧

技巧1:使用Tab补全

  • 输入命令或参数的一部分,按Tab键自动补全

技巧2:使用管道组合命令

Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU -Descending | Select-Object -First 5

技巧3:使用别名简化命令

# 查看别名
Get-Alias

# 常用别名
ls = Get-ChildItem
cd = Set-Location
cp = Copy-Item
mv = Move-Item
rm = Remove-Item
cat = Get-Content

技巧4:使用变量存储结果

$largeFiles = Get-ChildItem -Path C:\ -Recurse -File | Where-Object {$_.Length -gt 1GB}
$largeFiles | Select-Object FullName, @{N='Size(GB)';E={[math]::Round($_.Length/1GB,2)}}

通过本文的学习,你已经掌握了PowerShell的核心命令和实用技巧。PowerShell是Windows系统管理的利器,熟练使用它可以大幅提升工作效率。配合晨枫PE工具箱,你可以在各种场景下快速完成系统维护任务。建议多加练习,逐步掌握更多高级用法。