PowerShell 指令指南
本指南将介绍在 Windows 系统中使用 PowerShell 的常用命令,涵盖文件操作、系统管理及自动化脚本,同时比较它与 CMD 的核心区别,以及更强大的使用场景。
🔍 PowerShell vs CMD:核心区别
特性 | CMD | PowerShell |
---|---|---|
脚本支持 | .bat 、.cmd | .ps1 |
对象支持 | 文本流 | 原生支持对象(Object Pipeline) |
管道行为 | 传字符串 | 传递结构化对象 |
扩展性 | 有限 | 支持模块、函数、远程执行 |
自动化能力 | 基础级别 | 企业级自动化与 DevOps 支持 |
info
PowerShell 的强大在于它不仅是命令行工具,更是一个完整的脚本编程环境。
📁 常用文件与目录操作
Get-ChildItem # 类似 dir / ls
Set-Location .. # 切换目录
New-Item -Name "file.txt" -ItemType "file" # 创建文件
Remove-Item file.txt # 删除文件
使用别名操作更简单
ls
是Get-ChildItem
的别名cd
是Set-Location
的别名rm
是Remove-Item
的别名
📄 文本内容操作
Get-Content .\file.txt # 查看文件内容
Set-Content .\file.txt "Hello" # 写入文件
Add-Content .\file.txt "World" # 追加内容
⚙️ 系统管理命令
Get-Process # 查看进程
Stop-Process -Id 1234 # 终止进程
Get-Service # 查看所有服务
Start-Service "Spooler" # 启动服务
Stop-Service "Spooler" # 停止服务
caution
修改系统服务可能会影响操作系统的运行,请谨慎使用。
🌐 网络管理
Test-Connection google.com # 测试连通性(类似 ping)
Get-NetIPAddress # 查看 IP 地址
Get-NetTCPConnection # 查看端口占用
🔧 安装与模块管理
Install-Module -Name PSReadLine # 安装模块(第一次需使用管理员权限)
Get-Module -ListAvailable # 查看已安装模块
点击展开:配置 NuGet 提示
首次使用 Install-Module
时 PowerShell 会提示安装 NuGet 提供程序:
Install-PackageProvider -Name NuGet -Force
🧩 脚本与自动化示例
保存为 hello.ps1
:
$name = "World"
Write-Output "Hello, $name!"
运行脚本前需设置执行权限:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
.\hello.ps1
📦 示例:备份日志脚本
$Date = Get-Date -Format yyyy-MM-dd
$Source = "C:\Logs"
$Destination = "C:\Backup\Logs\$Date"
New-Item -ItemType Directory -Path $Destination -Force
Copy-Item "$Source\*.log" -Destination $Destination
Write-Host "日志已备份到 $Destination"
🧠 对象管道的强大之处
- PowerShell
- CMD
Get-Process | Where-Object { $_.CPU -gt 100 } | Sort-Object CPU -Descending
tasklist | find "chrome"
:: 无法进行数值计算和对象排序
tip
PowerShell 的 |
(管道)不仅传输文本,更传递结构化的 .NET 对象。
✅ 总结
- PowerShell 比 CMD 更现代、灵活,适合复杂自动化
- 支持结构化对象、模块化脚本、远程操作等企业级特性
- 是 DevOps、系统管理员及高级开发者首选命令行环境