Windows——PowerShell

PowerShell

一、概述

1.1、什么是PowerShell

PowerShell是微软开发的任务自动化框架,包含:

  • 命令行shell
  • 脚本语言
  • 配置管理框架

1.2、启动PowerShell

powershell 复制代码
# 方法1: 开始菜单搜索"PowerShell"
# 方法2: 运行对话框输入"powershell"
# 方法3: CMD中输入"powershell"
# 方法4: Win+X 选择"Windows PowerShell"

1.3、执行策略设置(首次使用)

powershell 复制代码
# 查看当前执行策略
Get-ExecutionPolicy

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

# 选项说明:
# - Restricted: 默认,禁止脚本运行
# - RemoteSigned: 运行本地脚本,远程脚本需数字签名
# - Unrestricted: 允许所有脚本运行

二、基本命令结构

2.1、动词-名词命名规范

PowerShell使用一致性命名:

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

三、系统信息命令

3.1、获取系统信息

shell 复制代码
# 获取计算机信息
Get-ComputerInfo

# 获取操作系统信息
Get-CimInstance Win32_OperatingSystem

# 获取计算机名称
hostname
# 或
$env:COMPUTERNAME

# 获取当前用户
whoami

3.2、硬件信息查询

powershell 复制代码
# 获取CPU信息
Get-CimInstance Win32_Processor

# 获取内存信息
Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum

# 获取磁盘信息
Get-Disk
Get-Volume

# 获取网络适配器
Get-NetAdapter

四、文件和目录操作

4.1、导航和浏览

shell 复制代码
# 显示当前目录
Get-Location
# 或
pwd

# 切换目录
Set-Location C:\Windows
# 或
cd C:\Windows

# 显示目录内容
Get-ChildItem
# 或
ls
# 或
dir

# 递归显示子目录
Get-ChildItem -Recurse

# 过滤显示
Get-ChildItem *.txt
Get-ChildItem -Filter "*.log"

4.2、文件操作

shell 复制代码
# 创建新文件
New-Item example.txt -ItemType File

# 创建目录
New-Item "NewFolder" -ItemType Directory

# 复制文件
Copy-Item source.txt destination.txt

# 移动文件
Move-Item old.txt new.txt

# 删除文件
Remove-Item file.txt

# 重命名文件
Rename-Item oldname.txt newname.txt

4.3、文件内容操作

shell 复制代码
# 读取文件内容
Get-Content file.txt

# 读取前几行
Get-Content file.txt -TotalCount 10

# 写入文件
"Hello World" | Out-File file.txt

# 追加内容
"New line" | Out-File file.txt -Append

# 清空文件
Clear-Content file.txt

五、进程和服务管理

5.1、进程管理

shell 复制代码
# 获取运行中的进程
Get-Process
# 或
ps

# 按名称过滤进程
Get-Process notepad

# 结束进程
Stop-Process -Name notepad
Stop-Process -ID 1234

# 启动进程
Start-Process notepad
Start-Process "C:\Program Files\App\app.exe"

5.2、服务管理

shell 复制代码
# 获取所有服务
Get-Service

# 按状态过滤服务
Get-Service | Where-Object {$_.Status -eq "Running"}

# 启动服务
Start-Service -Name "Spooler"

# 停止服务
Stop-Service -Name "Spooler"

# 重启服务
Restart-Service -Name "Spooler"

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

六、网络相关命令

6.1、网络配置

shell 复制代码
# 获取IP配置
Get-NetIPConfiguration

# 获取IP地址
Get-NetIPAddress

# 获取网络适配器
Get-NetAdapter

# 测试网络连接
Test-NetConnection google.com
Test-NetConnection -ComputerName 8.8.8.8 -Port 80

# 类似于ping
Test-Connection google.com

6.2、网络诊断

shell 复制代码
# 解析DNS
Resolve-DnsName google.com

# 获取TCP连接
Get-NetTCPConnection

# 路由表
Get-NetRoute

# 防火墙规则
Get-NetFirewallRule

七、系统管理命令

7.1、用户和组管理

shell 复制代码
# 获取本地用户
Get-LocalUser

# 创建新用户
New-LocalUser -Name "john" -Description "Test User"

# 获取本地组
Get-LocalGroup

# 添加用户到组
Add-LocalGroupMember -Group "Administrators" -Member "john"

# 获取组成员
Get-LocalGroupMember -Group "Administrators"

7.2、事件日志

shell 复制代码
# 获取事件日志
Get-EventLog -List

# 查看系统日志
Get-EventLog -LogName System -Newest 10

# 查看应用程序日志
Get-EventLog -LogName Application -EntryType Error

# 使用Get-WinEvent(更现代)
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2} -MaxEvents 5

八、管道操作

8.1、管道基础

shell 复制代码
# 基本管道
Get-Process | Where-Object {$_.CPU -gt 100}

# 排序结果
Get-Process | Sort-Object CPU -Descending

# 选择特定属性
Get-Process | Select-Object Name, CPU, WorkingSet

# 分组统计
Get-Process | Group-Object Company

8.2、数据处理示例

shell 复制代码
# 获取前5个CPU使用率最高的进程
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

# 按公司分组统计进程
Get-Process | Group-Object Company | Sort-Object Count -Descending

# 导出为CSV
Get-Process | Export-Csv processes.csv -NoTypeInformation

九、使用的单行命令

9.1、系统监控

shell 复制代码
# 查看系统启动时间
(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime

# 查看磁盘空间
Get-Volume | Select-Object DriveLetter, SizeRemaining, Size

# 查看内存使用情况
Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize, FreePhysicalMemory

# 查看前10大文件
Get-ChildItem C:\ -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10

9.2、实用用具

shell 复制代码
# 生成随机密码
-join ((33..126) | Get-Random -Count 12 | % {[char]$_})

# 计算文件夹大小
Get-ChildItem C:\Windows -Recurse | Measure-Object -Property Length -Sum

# 查找大文件
Get-ChildItem C:\ -Recurse -File | Where-Object {$_.Length -gt 100MB}

十、脚本编写基础

10.1、基本脚本结构

shell 复制代码
# 示例脚本:system_info.ps1
param(
    [string]$ComputerName = $env:COMPUTERNAME
)

Write-Host "系统信息报告" -ForegroundColor Green
Write-Host "计算机名: $ComputerName"
Write-Host "当前用户: $env:USERNAME"
Write-Host "报告时间: $(Get-Date)"

# 获取系统信息
$os = Get-CimInstance Win32_OperatingSystem
Write-Host "系统运行时间: $((Get-Date) - $os.LastBootUpTime)"

10.2、函数定义

shell 复制代码
function Get-SystemHealth {
    param($ComputerName = "localhost")
    
    $report = @{
        ComputerName = $ComputerName
        Timestamp = Get-Date
        CPUUsage = (Get-Counter "\Processor(_Total)\% Processor Time").CounterSamples.CookedValue
        MemoryUsage = (Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory
    }
    
    return $report
}

# 使用函数
Get-SystemHealth

十一、远程管理命令

11.1、远程会话

shell 复制代码
# 建立远程会话
Enter-PSSession -ComputerName Server01

# 执行远程命令
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }

# 在多个计算机上执行命令
$computers = "Server01", "Server02", "Server03"
Invoke-Command -ComputerName $computers -ScriptBlock { Get-Process }

11.2、远程文件操作

shell 复制代码
# 复制文件到远程计算机
Copy-Item -Path "C:\file.txt" -Destination "\\Server01\C$\temp\" -ToSession (New-PSSession Server01)

# 从远程计算机复制文件
Copy-Item -Path "\\Server01\C$\logs\app.log" -Destination "C:\temp\" -FromSession (New-PSSession Server01)

十二、模块管理

12.1、模块操作

shell 复制代码
# 查看已安装模块
Get-Module -ListAvailable

# 导入模块
Import-Module ActiveDirectory

# 查找可用模块
Find-Module -Name *Azure*

# 安装新模块
Install-Module -Name PSWindowsUpdate

# 更新模块
Update-Module

12.2、常用模块

shell 复制代码
# Active Directory 模块
Get-ADUser -Filter *
Get-ADComputer -Filter *

# Azure 模块
Connect-AzAccount
Get-AzVM

# Exchange 模块
Get-Mailbox

十三、错误处理和调试

13.1、错误处理

shell 复制代码
# 基本错误处理
try {
    Get-Content "nonexistent.txt" -ErrorAction Stop
}
catch {
    Write-Host "错误: $($_.Exception.Message)" -ForegroundColor Red
}

# 继续执行并记录错误
Get-Content "file.txt" -ErrorAction SilentlyContinue -ErrorVariable err
if ($err) {
    Write-Host "读取文件时出错"
}

13.2、调试技巧

shell 复制代码
# 设置调试偏好
$DebugPreference = "Continue"

# 调试输出
Write-Debug "调试信息"

# 详细输出
Write-Verbose "详细信息" -Verbose

# 设置断点
Set-PSBreakpoint -Script script.ps1 -Line 10

十四、实用脚本示例

14.1、系统健康检查脚本

shell 复制代码
# system_health.ps1
param($ComputerName = "localhost")

Write-Host "=== 系统健康检查 ===" -ForegroundColor Cyan
Write-Host "目标计算机: $ComputerName"
Write-Host "检查时间: $(Get-Date)"
Write-Host ""

# 检查磁盘空间
Write-Host "磁盘空间检查:" -ForegroundColor Yellow
Get-Volume | Where-Object {$_.DriveLetter} | 
    Select-Object DriveLetter, 
        @{Name="Size(GB)";Expression={[math]::Round($_.Size/1GB,2)}},
        @{Name="Free(GB)";Expression={[math]::Round($_.SizeRemaining/1GB,2)}},
        @{Name="Free(%)";Expression={[math]::Round(($_.SizeRemaining/$_.Size)*100,2)}}

# 检查服务状态
Write-Host "`n关键服务状态:" -ForegroundColor Yellow
$services = "Spooler", "Themes", "AudioSrv"
Get-Service -Name $services | 
    Select-Object Name, Status, StartType

# 检查事件日志错误
Write-Host "`n最近系统错误:" -ForegroundColor Yellow
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2} -MaxEvents 5 |
    Select-Object TimeCreated, Id, LevelDisplayName, Message

14.2、文件清理脚本

shell 复制代码
# cleanup_script.ps1
param(
    [string]$Path = "C:\Temp",
    [int]$DaysOld = 30
)

Write-Host "开始清理 $Path 中超过 $DaysOld 天的文件..." -ForegroundColor Green

$cutoffDate = (Get-Date).AddDays(-$DaysOld)
$files = Get-ChildItem $Path -Recurse -File | 
    Where-Object {$_.LastWriteTime -lt $cutoffDate}

if ($files.Count -eq 0) {
    Write-Host "没有找到符合条件的文件" -ForegroundColor Yellow
    exit
}

Write-Host "找到 $($files.Count) 个文件待清理" -ForegroundColor Yellow

# 显示将要删除的文件
$files | Select-Object Name, Length, LastWriteTime | Format-Table

$confirmation = Read-Host "确认删除这些文件? (y/n)"
if ($confirmation -eq 'y') {
    $files | Remove-Item -Verbose
    Write-Host "文件清理完成" -ForegroundColor Green
} else {
    Write-Host "操作已取消" -ForegroundColor Red
}

十五、性能优化技巧

15.1、提高执行效率

shell 复制代码
# 使用Where-Object过滤大量数据时
Get-Process | Where-Object {$_.Name -eq "notepad"}

# 更高效的方式(如果支持)
Get-Process -Name "notepad"

# 批量操作使用管道
1..100 | ForEach-Object { 
    New-Item "file$_.txt" -ItemType File 
}

# 使用工作流并行处理
workflow Invoke-ParallelProcess {
    foreach -parallel ($computer in $computers) {
        Get-Service -ComputerName $computer
    }
}

十六、常用别名对照

PowerShell命令 别名 CMD等价命令
Get-ChildItem dir, ls dir
Set-Location cd, chdir cd
Get-Content cat, type type
Copy-Item cp, copy copy
Remove-Item del, rm del
Get-Process ps tasklist
Stop-Process kill taskkill
相关推荐
极简之美3 小时前
Mac 远程连接 Windows 简明教程(2025 实测版)
windows·macos
电脑小管家3 小时前
蝰蛇鼠标驱动怎么安装?全型号驱动下载方法汇总
windows·驱动开发·计算机外设·电脑·游戏程序
无限进步_3 小时前
C++从入门到类和对象完全指南
开发语言·c++·windows·git·后端·github·visual studio
陈鋆4 小时前
Langchain-Chatchat[三、知识库管理的 RAG]
windows·langchain
浪客川4 小时前
高效日志分离器:一键筛选关键信息
开发语言·windows·c#
7***99874 小时前
Redis——Windows安装
数据库·windows·redis
love530love4 小时前
【ComfyUI/SD环境管理指南(二)】:如何避免插件安装导致的环境崩溃与“外科手术式”修复
人工智能·windows·python·stable diffusion·github·aigc·comfyui
聪明努力的积极向上4 小时前
【WINDOWS】电脑外接显示屏突然无效(戴尔Inspiron 15 3511)
windows·电脑
陈聪.5 小时前
MySQL全平台安装指南:Windows与Linux详细教程
linux·windows·mysql