实用的 PowerShell 命令

以下是一些常用但不乏实用的 PowerShell 命令,涵盖系统信息、文件操作、网络诊断、进程管理、自动化等多个方面,适合管理员、开发者或脚本爱好者使用。

一、系统信息查询

powershell复制编辑# 查看操作系统版本
Get-ComputerInfo | Select-Object OsName, OsArchitecture, WindowsVersion
# 查看内存信息(单位:GB)
Get-CimInstance Win32_ComputerSystem | Select-Object TotalPhysicalMemory | ForEach-Object { "{0:N2} GB" -f ($_.TotalPhysicalMemory / 1GB) }
# 查看系统启动时间
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime
# 查看显卡信息
Get-WmiObject Win32_VideoController | Select-Object Name, DriverVersion

二、网络相关命令

powershell复制编辑# 查看本机IP地址
Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' -and $_.IPAddress -notlike '169.*' }

# 测试网络连通性(ping)
Test-Connection -ComputerName www.baidu.com -Count 4

# 查看当前打开的端口(类似 netstat)
Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' } | Select-Object LocalAddress, LocalPort

# 查看DNS缓存
Get-DnsClientCache

三、进程与服务管理

powershell复制编辑# 查看运行中的进程
Get-Process
# 杀掉指定进程
Stop-Process -Name notepad -Force
# 查看所有服务及状态
Get-Service | Sort-Object Status
# 启动服务
Start-Service -Name wuauserv
# 停止服务
Stop-Service -Name wuauserv

四、文件与文件夹操作

powershell复制编辑# 列出当前目录下所有文件
Get-ChildItem
# 递归查找某类文件(如 .log)
Get-ChildItem -Recurse -Filter *.log
# 复制文件
Copy-Item "C:\a.txt" -Destination "D:\backup\a.txt"
# 移动文件
Move-Item "C:\a.txt" -Destination "D:\"
# 删除文件/文件夹(慎用 -Recurse)
Remove-Item "C:\temp\*" -Recurse -Force

五、文本处理和日志分析

powershell复制编辑# 读取文本文件内容
Get-Content "C:\logs\example.log"
# 查找包含关键字的行
Select-String -Path "C:\logs\example.log" -Pattern "ERROR"
# 统计出现次数
Select-String -Path "C:\logs\example.log" -Pattern "ERROR" | Group-Object Line | Sort-Object Count -Descending

六、定时任务与自动化

powershell复制编辑# 创建计划任务(每天 9 点运行脚本)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "C:\scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "DailyBackup" -Description "每日备份任务"

七、用户与权限

powershell复制编辑# 查看当前用户
whoami
# 添加本地用户
New-LocalUser "testuser" -Password (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)
# 添加用户到管理员组
Add-LocalGroupMember -Group "Administrators" -Member "testuser"

八、实用杂项技巧

powershell复制编辑# 清屏
Clear-Host
# 当前目录打开文件资源管理器
ii .
# 打开记事本并载入文件
notepad C:\Windows\System32\drivers\etc\hosts
# 快速提权运行 PowerShell(需管理员权限)
Start-Process powershell -Verb runAs

发表回复