PowerShell 自动化脚本入门指南
PowerShell是Windows系统强大的自动化工具。本文介绍基础脚本编写。
1. 基础语法
# 输出Hello World
Write-Host "Hello PowerShell!"
2. 变量使用
$name = "OpenClaw"
Write-Host "Hello, $name!"
3. 函数定义
function Get-SystemInfo {
param([string]$ComputerName = $env:COMPUTERNAME)
$os = Get-CimInstance Win32_OperatingSystem
$cpu = Get-CimInstance Win32_Processor
[PSCustomObject]@{
ComputerName = $ComputerName
OS = $os.Caption
Version = $os.Version
CPU = $cpu.Name
Cores = $cpu.NumberOfCores
}
}
# 使用函数
Get-SystemInfo
4. 错误处理
try {
# 尝试执行可能失败的操作
Get-Process -Name "NonExistentProcess" -ErrorAction Stop
} catch {
Write-Host "错误发生: $_" -ForegroundColor Red
} finally {
Write-Host "脚本执行完成" -ForegroundColor Green
}
5. 实用脚本示例
# 系统信息收集脚本
$report = @()
$report += "=== 系统信息报告 ==="
$report += "生成时间: $(Get-Date)"
$report += ""
# 操作系统信息
$os = Get-CimInstance Win32_OperatingSystem
$report += "操作系统: $($os.Caption)"
$report += "版本: $($os.Version)"
$report += "安装日期: $($os.InstallDate)"
# 内存信息
$memory = Get-CimInstance Win32_ComputerSystem
$totalMemory = [math]::Round($memory.TotalPhysicalMemory / 1GB, 2)
$report += "总内存: ${totalMemory} GB"
# 磁盘信息
$disks = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"
foreach ($disk in $disks) {
$sizeGB = [math]::Round($disk.Size / 1GB, 2)
$freeGB = [math]::Round($disk.FreeSpace / 1GB, 2)
$usedGB = $sizeGB - $freeGB
$usedPercent = [math]::Round(($usedGB / $sizeGB) * 100, 2)
$report += "磁盘 $($disk.DeviceID): ${sizeGB}GB (已用: ${usedPercent}%)"
}
# 输出报告
$report | ForEach-Object { Write-Host $_ }
6. 脚本保存和运行
- 将代码保存为 .ps1 文件
- 以管理员身份运行PowerShell
- 执行脚本:
.\scriptname.ps1 - 如果需要运行未签名脚本,先执行:
Set-ExecutionPolicy RemoteSigned
学习资源
- Microsoft PowerShell文档
- PowerShell Gallery(脚本库)
- 在线教程和视频课程
本文由 OpenClaw 自动生成并发布,专注于提供实用的技术解决方案。
原创文章,作者:技术老牛,如若转载,请注明出处:https://jishubiji.com/p/754