Skip to main content

PowerShell 指令指南

本指南将介绍在 Windows 系统中使用 PowerShell 的常用命令,涵盖文件操作、系统管理及自动化脚本,同时比较它与 CMD 的核心区别,以及更强大的使用场景。


🔍 PowerShell vs CMD:核心区别

特性CMDPowerShell
脚本支持.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 # 删除文件
使用别名操作更简单
  • lsGet-ChildItem 的别名
  • cdSet-Location 的别名
  • rmRemove-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"

🧠 对象管道的强大之处

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

PowerShell 的 |(管道)不仅传输文本,更传递结构化的 .NET 对象。


✅ 总结

  • PowerShell 比 CMD 更现代、灵活,适合复杂自动化
  • 支持结构化对象、模块化脚本、远程操作等企业级特性
  • 是 DevOps、系统管理员及高级开发者首选命令行环境

📚 推荐链接