Skip to content

PowerShell 详细介绍

什么是 PowerShell

PowerShell 是微软开发的跨平台任务自动化和配置管理框架,由命令行 shell 和脚本语言组成。它最初于 2006 年发布,设计目标是帮助系统管理员和高级用户自动化管理任务。

PowerShell 的核心特点

  1. 面向对象:PowerShell 基于 .NET 框架,处理的是 .NET 对象而非纯文本,这使得数据处理更加灵活和强大。

  2. Cmdlet 命令体系:PowerShell 使用称为 "cmdlet"(读作 command-let)的轻量级命令,遵循 动词-名词 的命名规范,如 Get-ProcessSet-LocationNew-Item 等。

  3. 管道传递对象:与 CMD 不同,PowerShell 的管道传递的是完整的 .NET 对象,而非文本流,允许更复杂的数据操作。

  4. 强大的脚本语言:支持变量、循环、条件判断、函数、类、异常处理等完整的编程语言特性。

  5. 跨平台支持:PowerShell Core(PowerShell 6+)支持 Windows、Linux 和 macOS。

PowerShell 版本历史

版本说明
PowerShell 1.02006 年发布,仅支持 Windows
PowerShell 2.0内置于 Windows 7,引入远程管理、后台作业
PowerShell 3.0内置于 Windows 8,引入工作流、自动模块加载
PowerShell 4.0内置于 Windows 8.1,增强 DSC
PowerShell 5.0/5.1内置于 Windows 10,引入类定义
PowerShell 6+ (Core)跨平台版本,基于 .NET Core
PowerShell 7.x当前最新版本,持续更新

PowerShell 与 CMD 的详细区别

1. 底层架构差异

CMD (Command Prompt)

  • 基于 MS-DOS 命令行解释器
  • 16/32 位应用程序
  • 仅处理文本字符串
  • 单一执行环境

PowerShell

  • 基于 .NET Framework / .NET Core
  • 完全面向对象
  • 处理 .NET 对象
  • 支持多种运行模式(交互式、脚本、远程)

2. 命令语法对比

命令格式

操作CMDPowerShell
列出目录内容dirGet-ChildItem (别名: dir, ls)
切换目录cdSet-Location (别名: cd)
复制文件copyCopy-Item (别名: cp, copy)
删除文件delRemove-Item (别名: del, rm)
查看进程tasklistGet-Process
结束进程taskkill /PID xxxStop-Process -Id xxx
查看服务sc queryGet-Service
网络配置ipconfigGet-NetIPConfiguration

命令参数风格

CMD 参数风格:

cmd
dir /w /p
tasklist /fi "status eq running"
xcopy source dest /e /h /c

PowerShell 参数风格:

powershell
Get-ChildItem -Width -Paging
Get-Process | Where-Object { $_.Status -eq "Running" }
Copy-Item -Path source -Destination dest -Recurse -Force

3. 数据处理方式

CMD - 文本处理

cmd
REM CMD 只能处理文本,需要借助 find、findstr 等
dir | find "txt"

PowerShell - 对象处理

powershell
Get-ChildItem | Where-Object { $_.Extension -eq ".txt" }
Get-ChildItem | Select-Object Name, Length, LastWriteTime
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

4. 变量系统

CMD 变量

cmd
@echo off
set name=John
set /a number=10
echo %name%
echo %number%

限制:

  • 只有字符串和整数类型
  • 作用域全局
  • 无数组支持(需模拟)
  • 无复杂数据结构

PowerShell 变量

powershell
$name = "John"
$number = 10
$pi = 3.14159
$isActive = $true
$date = Get-Date

$array = @(1, 2, 3, 4, 5)
$hash = @{ Name = "John"; Age = 30 }

$processes = Get-Process
$processes[0].ProcessName

优势:

  • 支持所有 .NET 数据类型
  • 作用域控制(global, script, local)
  • 数组、哈希表、自定义对象
  • 类型推断和强类型

5. 脚本能力对比

CMD 批处理脚本

cmd
@echo off
setlocal enabledelayedexpansion

for /l %%i in (1,1,10) do (
    echo Number: %%i
)

if exist file.txt (
    echo File exists
) else (
    echo File not found
)

PowerShell 脚本

powershell
for ($i = 1; $i -le 10; $i++) {
    Write-Host "Number: $i"
}

if (Test-Path "file.txt") {
    Write-Host "File exists"
} else {
    Write-Host "File not found"
}

function Get-Sum {
    param([int[]]$Numbers)
    return ($Numbers | Measure-Object -Sum).Sum
}

Get-Sum -Numbers @(1,2,3,4,5)

6. 管道系统

CMD 管道

cmd
type file.txt | find "error" | sort
  • 只能传递文本
  • 处理能力有限

PowerShell 管道

powershell
Get-EventLog -LogName Application -Newest 100 |
    Where-Object { $_.EntryType -eq "Error" } |
    Select-Object TimeGenerated, Source, Message |
    Sort-Object TimeGenerated -Descending |
    Export-Csv -Path "errors.csv" -NoTypeInformation
  • 传递完整对象
  • 支持链式复杂操作
  • 每个阶段可访问对象属性和方法

7. 远程管理能力

CMD

  • 仅支持 psexec 等外部工具
  • 功能有限
  • 安全性较低

PowerShell

powershell
Enable-PSRemoting -Force
Enter-PSSession -ComputerName Server01
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { Get-Service }
  • 原生支持远程会话
  • 支持并行远程执行
  • WinRM 安全协议

8. 错误处理

CMD

cmd
if errorlevel 1 (
    echo Command failed
)
  • 只能检查退出码
  • 无异常处理机制

PowerShell

powershell
try {
    Get-Content "nonexistent.txt" -ErrorAction Stop
} catch [System.IO.FileNotFoundException] {
    Write-Error "File not found: $_"
} catch {
    Write-Error "Unexpected error: $_"
} finally {
    Write-Host "Cleanup operations"
}
  • 完整的 try-catch-finally
  • 详细的异常对象
  • 可自定义错误处理

9. 模块和扩展性

CMD

  • 功能固定
  • 依赖外部工具扩展
  • 无包管理

PowerShell

powershell
Get-Module -ListAvailable
Import-Module ActiveDirectory
Find-Module *azure* | Install-Module

Get-Command -Module ActiveDirectory
  • 模块化架构
  • PowerShell Gallery 包管理
  • 可自定义模块和 cmdlet

10. 安全特性

CMD

  • 无执行策略限制
  • 脚本可直接运行
  • 安全性较低

PowerShell

powershell
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned

Restricted      # 不允许运行脚本
RemoteSigned    # 本地脚本可运行,远程需签名
AllSigned       # 所有脚本需签名
Unrestricted    # 允许所有脚本
Bypass          # 不阻止任何脚本
  • 执行策略控制
  • 脚本签名支持
  • 审计日志
  • Just Enough Administration (JEA)

11. 输出格式化

CMD

cmd
dir
tasklist
  • 固定输出格式
  • 难以自定义

PowerShell

powershell
Get-Process | Format-Table Name, CPU, Memory -AutoSize
Get-Process | Format-List *
Get-Service | Format-Wide -Column 4
Get-Process | Out-GridView
Get-ChildItem | Out-File "output.txt"
  • 多种输出格式
  • 可自定义视图
  • 支持图形化输出

12. 性能考量

方面CMDPowerShell
启动速度较慢(加载 .NET)
简单命令稍慢
复杂操作需多次调用单次管道完成
内存占用较高
大规模数据处理困难高效(流式处理)

13. 兼容性

CMD

  • 仅 Windows 平台
  • 向后兼容 DOS 命令
  • 遗留系统支持

PowerShell

  • Windows PowerShell (5.1) - 仅 Windows
  • PowerShell Core (6+) - 跨平台
  • 通过别名兼容部分 CMD 命令
  • 可调用 CMD 命令:cmd /c dir

14. 使用场景建议

选择 CMD 的情况

  • 简单的批处理任务
  • 需要快速启动
  • 遗留脚本维护
  • 系统恢复环境
  • 对启动速度要求极高

选择 PowerShell 的情况

  • 系统管理自动化
  • 复杂脚本开发
  • 远程服务器管理
  • 云资源管理(Azure、AWS)
  • CI/CD 流程
  • 数据处理和分析
  • 需要面向对象处理
  • 跨平台脚本需求

15. 互操作性

PowerShell 可以调用 CMD 命令:

powershell
cmd /c "echo Hello from CMD"
& cmd.exe /c "dir /w"

CMD 可以调用 PowerShell:

cmd
powershell -Command "Get-Process | Select-Object -First 5"
powershell -File "script.ps1"

总结对比表

特性CMDPowerShell
发布年份1987 (MS-DOS)2006
架构文本处理面向对象
平台仅 Windows跨平台
命令系统内置命令Cmdlet + 模块
管道文本流对象流
脚本语言批处理完整编程语言
变量类型字符串/整数所有 .NET 类型
错误处理退出码异常处理
远程管理有限原生支持
模块系统
包管理PowerShell Gallery
执行策略
学习曲线简单中等
功能强度基础强大

学习资源

基于 VitePress 的本地知识库