Skip to content

PowerShell 入门

PowerShell 是 Windows 系统中功能强大的命令行工具和脚本语言,相比传统的 CMD,它提供了更丰富的功能和更现代化的编程体验。

PowerShell 简介

什么是 PowerShell

PowerShell 是微软开发的任务自动化和配置管理框架,它包含:

  • 命令行界面:交互式的命令行环境
  • 脚本语言:基于 .NET 的脚本语言
  • 命令(Cmdlet):内置的系统管理命令
  • 管道:强大的对象管道系统

PowerShell 与 CMD 的区别

特性CMDPowerShell
对象处理文本对象
命令命名不统一动词-名词格式
别名支持有限丰富
脚本能力批处理完整编程语言
.NET 集成深度集成

启动 PowerShell

有多种方式可以启动 PowerShell:

powershell
# 方式一:通过开始菜单搜索 "PowerShell"

# 方式二:通过运行对话框(Win + R)
powershell

# 方式三:以管理员身份运行
# 右键点击开始菜单 -> Windows PowerShell (管理员)

# 方式四:从 CMD 切换到 PowerShell
powershell

PowerShell 版本

powershell
# 查看 PowerShell 版本
$PSVersionTable.PSVersion

# 查看详细信息
$PSVersionTable

基本命令

Cmdlet 命令格式

PowerShell 命令(Cmdlet)采用"动词-名词"的命名格式:

powershell
# 命令格式:动词-名词
# Get-Command  获取命令
# Get-Process  获取进程
# Get-Service  获取服务
# New-Item     创建项目
# Remove-Item  删除项目

# 获取所有可用的命令
Get-Command

# 获取特定动词的命令
Get-Command -Verb Get

# 获取特定名词的命令
Get-Command -Noun Process

常用基本命令

powershell
# 清屏
Clear-Host
cls  # 别名

# 显示当前日期时间
Get-Date

# 显示日历
Show-Calendar

# 查看当前目录
Get-Location
pwd  # 别名

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

# 列出目录内容
Get-ChildItem
ls      # 别名
dir     # 别名

# 查看命令帮助
Get-Help Get-Process
Get-Help Get-Process -Detailed
Get-Help Get-Process -Examples

# 获取命令的详细信息
Get-Command Get-Process | Format-List *

别名系统

PowerShell 为常用命令提供了别名,方便用户记忆:

powershell
# 查看命令的别名
Get-Alias -Definition Get-ChildItem

# 查看别名对应的命令
Get-Alias ls

# 创建自定义别名
Set-Alias -Name ll -Value Get-ChildItem

# 常用别名对照表
# ls -> Get-ChildItem
# cd -> Set-Location
# pwd -> Get-Location
# cp -> Copy-Item
# mv -> Move-Item
# rm -> Remove-Item
# cat -> Get-Content
# echo -> Write-Output
# cls -> Clear-Host

文件和目录操作

目录操作

powershell
# 创建目录
New-Item -Path "C:\TestFolder" -ItemType Directory
New-Item -Path ".\NewFolder" -ItemType Directory -Force  # 强制创建

# 删除目录
Remove-Item -Path "C:\TestFolder" -Recurse -Force
# -Recurse  递归删除子目录和文件
# -Force    强制删除只读文件

# 复制目录
Copy-Item -Path "C:\Source" -Destination "C:\Destination" -Recurse

# 移动/重命名目录
Move-Item -Path "C:\OldName" -Destination "C:\NewName"

# 检查目录是否存在
Test-Path "C:\Windows"

文件操作

powershell
# 创建文件
New-Item -Path "C:\test.txt" -ItemType File
New-Item -Path ".\script.ps1" -ItemType File

# 创建文件并写入内容
Set-Content -Path "C:\test.txt" -Value "Hello, PowerShell!"

# 追加内容到文件
Add-Content -Path "C:\test.txt" -Value "This is a new line."

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

# 读取文件前几行
Get-Content -Path "C:\test.txt" -TotalCount 5

# 读取文件最后几行
Get-Content -Path "C:\test.txt" -Tail 5

# 复制文件
Copy-Item -Path "C:\test.txt" -Destination "C:\backup\test.txt"

# 移动文件
Move-Item -Path "C:\test.txt" -Destination "C:\temp\"

# 删除文件
Remove-Item -Path "C:\test.txt" -Force

# 重命名文件
Rename-Item -Path "C:\old.txt" -NewName "new.txt"

搜索文件

powershell
# 搜索文件
Get-ChildItem -Path "C:\" -Filter "*.txt" -Recurse

# 搜索特定名称的文件
Get-ChildItem -Path "C:\" -Filter "config*" -Recurse

# 搜索并只显示文件名
Get-ChildItem -Path "C:\" -Filter "*.log" -Recurse | Select-Object FullName

# 搜索大文件(大于100MB)
Get-ChildItem -Path "C:\" -Recurse | Where-Object { $_.Length -gt 100MB }

# 搜索最近修改的文件
Get-ChildItem -Path "C:\" -Recurse | Sort-Object LastWriteTime -Descending | Select-Object -First 10

管道和对象

理解管道

PowerShell 的管道传递的是对象,而不是文本:

powershell
# 管道示例:获取进程并排序
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

# 管道示例:获取服务并筛选
Get-Service | Where-Object { $_.Status -eq "Running" }

# 管道示例:获取文件并导出
Get-ChildItem | Export-Csv -Path "files.csv"

常用管道命令

powershell
# Where-Object:筛选对象
Get-Process | Where-Object { $_.CPU -gt 100 }
Get-Service | Where-Object { $_.Status -eq "Stopped" }

# Select-Object:选择属性
Get-Process | Select-Object Name, CPU, WorkingSet
Get-Process | Select-Object -First 5  # 前5个
Get-Process | Select-Object -Last 5   # 后5个
Get-Process | Select-Object -Unique   # 唯一值

# Sort-Object:排序对象
Get-Process | Sort-Object CPU -Descending
Get-ChildItem | Sort-Object Length -Descending

# Group-Object:分组对象
Get-Service | Group-Object Status
Get-ChildItem | Group-Object Extension

# Measure-Object:统计对象
Get-ChildItem | Measure-Object -Property Length -Sum
Get-Process | Measure-Object -Property WorkingSet -Average

格式化输出

powershell
# 格式化为表格
Get-Process | Format-Table Name, CPU, WorkingSet -AutoSize

# 格式化为列表
Get-Process | Format-List Name, CPU, WorkingSet

# 格式化为宽列表
Get-Process | Format-Wide Name -Column 4

# 自定义表格
Get-Process | Format-Table @{Label="进程名"; Expression={$_.Name}}, 
                           @{Label="CPU时间"; Expression={$_.CPU}},
                           @{Label="内存(MB)"; Expression={[math]::Round($_.WorkingSet/1MB,2)}}

变量和数据类型

变量基础

powershell
# 创建变量
$name = "PowerShell"
$version = 7.0
$isActive = $true

# 变量命名规则
# - 以 $ 开头
# - 可以包含字母、数字、下划线
# - 不区分大小写

# 显示变量值
$name
Write-Host $name

# 获取变量类型
$name.GetType()

# 强类型变量
[int]$number = 100
[string]$text = "Hello"

# 删除变量
Remove-Variable name

特殊变量

powershell
# $_ - 当前管道对象
Get-Process | Where-Object { $_.CPU -gt 100 }

# $null - 空值
$value = $null

# $true 和 $false - 布尔值
$enabled = $true
$disabled = $false

# $PWD - 当前目录
$PWD

# $HOME - 用户主目录
$HOME

# $PSVersionTable - PowerShell 版本信息
$PSVersionTable

# $Error - 错误记录
$Error

# $? - 上一个命令的执行状态
$?

数组

powershell
# 创建数组
$numbers = 1, 2, 3, 4, 5
$names = @("张三", "李四", "王五")
$empty = @()

# 访问数组元素(索引从0开始)
$numbers[0]      # 第一个元素
$numbers[-1]     # 最后一个元素
$numbers[0..2]   # 前三个元素

# 数组长度
$numbers.Length

# 添加元素
$numbers += 6

# 遍历数组
foreach ($num in $numbers) {
    Write-Host $num
}

# 数组操作
$numbers | ForEach-Object { $_ * 2 }
$numbers | Where-Object { $_ -gt 2 }
$numbers | Sort-Object -Descending

哈希表

powershell
# 创建哈希表
$person = @{
    Name = "张三"
    Age = 25
    City = "北京"
}

# 访问值
$person.Name
$person["Age"]

# 添加键值对
$person.Email = "zhangsan@example.com"

# 修改值
$person.Age = 26

# 删除键值对
$person.Remove("City")

# 遍历哈希表
foreach ($key in $person.Keys) {
    Write-Host "$key = $($person[$key])"
}

# 有序哈希表
$ordered = [ordered]@{
    First = 1
    Second = 2
    Third = 3
}

控制流程

条件语句

powershell
# if 语句
$score = 85

if ($score -ge 90) {
    Write-Host "优秀"
} elseif ($score -ge 80) {
    Write-Host "良好"
} elseif ($score -ge 60) {
    Write-Host "及格"
} else {
    Write-Host "不及格"
}

# 比较运算符
# -eq  等于
# -ne  不等于
# -gt  大于
# -ge  大于等于
# -lt  小于
# -le  小于等于
# -like   通配符匹配
# -notlike 不匹配
# -match  正则匹配
# -notmatch 不匹配

# 逻辑运算符
# -and  与
# -or   或
# -not  非
# -xor  异或

# switch 语句
$day = "Monday"

switch ($day) {
    "Monday"    { Write-Host "星期一" }
    "Tuesday"   { Write-Host "星期二" }
    "Wednesday" { Write-Host "星期三" }
    Default     { Write-Host "其他" }
}

循环语句

powershell
# for 循环
for ($i = 1; $i -le 5; $i++) {
    Write-Host "计数: $i"
}

# foreach 循环
$fruits = @("苹果", "香蕉", "橙子")
foreach ($fruit in $fruits) {
    Write-Host "水果: $fruit"
}

# while 循环
$count = 0
while ($count -lt 5) {
    Write-Host $count
    $count++
}

# do-while 循环
$num = 0
do {
    Write-Host $num
    $num++
} while ($num -lt 3)

# do-until 循环
$num = 0
do {
    Write-Host $num
    $num++
} until ($num -ge 3)

# 循环控制
# break - 跳出循环
# continue - 跳过本次迭代

for ($i = 1; $i -le 10; $i++) {
    if ($i -eq 5) { continue }  # 跳过5
    if ($i -eq 8) { break }     # 到8停止
    Write-Host $i
}

函数

定义函数

powershell
# 简单函数
function SayHello {
    Write-Host "Hello, PowerShell!"
}

# 调用函数
SayHello

# 带参数的函数
function Greet {
    param(
        [string]$Name
    )
    Write-Host "你好, $Name!"
}

Greet -Name "张三"

# 带默认参数的函数
function GreetUser {
    param(
        [string]$Name = "访客",
        [int]$Age = 18
    )
    Write-Host "姓名: $Name, 年龄: $Age"
}

GreetUser
GreetUser -Name "李四" -Age 25

高级函数

powershell
# 带参数验证的函数
function Get-Grade {
    param(
        [Parameter(Mandatory=$true)]  # 必需参数
        [ValidateRange(0, 100)]       # 范围验证
        [int]$Score,
        
        [ValidateSet("A", "B", "C", "D", "F")]  # 集合验证
        [string]$Level = "C"
    )
    
    Write-Host "分数: $Score, 等级: $Level"
}

# 管道函数
function Get-Double {
    param(
        [Parameter(ValueFromPipeline=$true)]
        [int]$Number
    )
    
    process {
        $_ * 2
    }
}

# 使用管道
1..5 | Get-Double

# 返回值的函数
function Add-Numbers {
    param(
        [int]$a,
        [int]$b
    )
    
    return $a + $b
}

$result = Add-Numbers -a 10 -b 20
Write-Host "结果: $result"

脚本编写

创建脚本文件

powershell
# PowerShell 脚本文件扩展名为 .ps1
# 创建脚本文件:New-Item -Path "script.ps1" -ItemType File

# 脚本示例 (保存为 hello.ps1)
<#
.SYNOPSIS
    这是一个问候脚本
.DESCRIPTION
    该脚本接受用户名参数并输出问候语
.PARAMETER Name
    用户名
.EXAMPLE
    .\hello.ps1 -Name "张三"
#>

param(
    [string]$Name = "World"
)

Write-Host "Hello, $Name!"
Write-Host "当前时间: $(Get-Date)"

执行策略

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

# 执行策略类型:
# Restricted - 不允许运行脚本(默认)
# RemoteSigned - 本地脚本可运行,远程脚本需要签名
# Unrestricted - 允许所有脚本
# Bypass - 不阻止任何脚本

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

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

运行脚本

powershell
# 运行脚本(需要完整路径或相对路径)
.\script.ps1
C:\Scripts\script.ps1

# 传递参数
.\script.ps1 -Name "张三" -Age 25

# 调用运算符 &
& ".\script with spaces.ps1"

# 后台运行脚本
Start-Job -FilePath ".\longtask.ps1"

模块管理

模块基础

powershell
# 查看已安装的模块
Get-Module -ListAvailable

# 查看已加载的模块
Get-Module

# 导入模块
Import-Module ActiveDirectory

# 移除模块
Remove-Module ActiveDirectory

# 查看模块命令
Get-Command -Module ActiveDirectory

PowerShellGet

powershell
# PowerShellGet 是模块管理工具

# 查找模块
Find-Module -Name "Azure*"

# 安装模块
Install-Module -Name Az -Scope CurrentUser

# 更新模块
Update-Module -Name Az

# 卸载模块
Uninstall-Module -Name Az

# 保存模块(不安装)
Save-Module -Name Az -Path ".\Modules\"

# 查看已安装模块
Get-InstalledModule

远程管理

远程会话

powershell
# 启用远程管理(需要管理员权限)
Enable-PSRemoting -Force

# 创建远程会话
$session = New-PSSession -ComputerName "Server01"

# 在远程会话中执行命令
Invoke-Command -Session $session -ScriptBlock { Get-Process }

# 进入远程会话
Enter-PSSession -ComputerName "Server01"

# 退出远程会话
Exit-PSSession

# 关闭远程会话
Remove-PSSession -Session $session

远程执行

powershell
# 在远程计算机执行单个命令
Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Service }

# 在多台计算机执行命令
Invoke-Command -ComputerName "Server01","Server02" -ScriptBlock { Get-Process }

# 使用凭据连接
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock { Get-Process }

# 执行本地脚本
Invoke-Command -ComputerName "Server01" -FilePath ".\script.ps1"

实用技巧

命令历史

powershell
# 查看命令历史
Get-History

# 执行历史命令
Invoke-History 5  # 执行第5条命令

# 清除历史
Clear-History

# 使用上下箭头键浏览历史命令

# 搜索历史命令(Ctrl + R)

Tab 补全

powershell
# 按 Tab 键自动补全命令和参数
Get-Ch<Tab>      # 自动补全为 Get-ChildItem
Get-Process -<Tab>  # 循环显示可用参数

# 使用 Ctrl + Space 显示所有可能的补全

输出重定向

powershell
# 重定向到文件
Get-Process > processes.txt

# 追加到文件
Get-Process >> processes.txt

# 重定向错误输出
Get-Process 2> errors.txt

# 重定向所有输出
Get-Process *> all.txt

# 使用 Out-File
Get-Process | Out-File -FilePath "processes.txt" -Encoding UTF8

# 使用 Out-GridView(图形化显示)
Get-Process | Out-GridView

常用快捷键

快捷键功能
Ctrl + C取消当前命令
Ctrl + L清屏
Ctrl + R搜索历史命令
Ctrl + A移动到行首
Ctrl + E移动到行尾
Ctrl + ←向左移动一个词
Ctrl + →向右移动一个词
Tab自动补全
F7显示命令历史窗口
F8搜索历史命令

小结

本章介绍了 PowerShell 的基础知识:

  1. PowerShell 简介:了解 PowerShell 的特点和优势
  2. 基本命令:掌握 Cmdlet 命令格式和常用命令
  3. 文件操作:学习文件和目录的管理操作
  4. 管道和对象:理解 PowerShell 的核心概念
  5. 变量和数据类型:掌握变量的使用方法
  6. 控制流程:学习条件判断和循环语句
  7. 函数:了解函数的定义和使用
  8. 脚本编写:学习创建和运行 PowerShell 脚本
  9. 模块管理:掌握模块的安装和使用
  10. 远程管理:了解远程操作的方法

PowerShell 是 Windows 系统管理的强大工具,熟练掌握它可以大大提高工作效率。建议多加练习,逐步掌握更高级的功能。