🎬 HoRain 云小助手:个人主页
⛺️生活的理想,就是为了理想的生活!
⛳️ 推荐
前些天发现了一个超棒的服务器购买网站,性价比超高,大内存超划算!忍不住分享一下给大家。点击跳转到网站。
目录
⛳️ 推荐
PowerShell 基本语法完整指南
一、变量和数据类型
1. 变量声明与赋值
2. 常见数据类型
3. 常用类型转换
二、常用运算符
1. 赋值运算符
2. 比较运算符
3. 逻辑运算符
4. 集合运算符
三、流程控制语句
1. If 条件判断
2. For 循环
3. While 和 Do-While
4. 范围操作符
四、函数定义与调用
1. 基本函数
2. 带返回值的函数
3. 高级函数特性
4. 全局/私有限定词
五、管道和操作符
1. 管道传递
2. 特殊操作符
3. 管道重定向
六、数组和哈希表
1. 数组操作
2. 哈希表操作
七、错误处理
1. Try-Catch-Finally
2. 错误管理参数
3. 警告和调试信息
八、模块和别名
1. 模块管理
2. 常用内置命令别名
3. 创建自定义别名
九、环境配置和 Profile
1. Profile 文件
2. 常用 Profile 配置
十、实用完整示例
示例 1: 系统状态报告脚本
示例 2: 批量文件搜索工具
示例 3: 数据转换工具
十一、快速参考表
十二、最佳实践建议
PowerShell 基本语法完整指南
PowerShell 是基于 .NET 的对象导向自动化框架,与命令提示符有本质区别。以下是系统性的语法学习:
一、变量和数据类型
1. 变量声明与赋值
# 基本变量 $name = "John" $age = 30 $isStudent = $true $data = @() $path = "C:\Users\Name" # 变量名规范(推荐) $UserName # PascalCase 用于命令中访问 $myVariable # camelCase 通用 $env:PATH # 环境变量 # 查看变量 Get-Variable # 列出所有变量 $VARNAME -type Type # 检查类型 GetType -InputObject $name # 获取具体类型2. 常见数据类型
| 类型 | 示例 | 说明 |
|---|---|---|
[int] | $count = [int]"123" | 整数 |
[string] | $text = "Hello" | 字符串 |
[bool] | $flag = $true | 布尔值 |
[array] | $list = @(1,2,3) | 数组 |
[hashtable] | $hash = @{Key="Value"} | 字典/哈希表 |
[datetime] | $now = Get-Date | 日期时间 |
[decimal] | $price = 99.99M | 高精度小数 |
3. 常用类型转换
# 强制类型转换 [bool]$flag = "True" # true [int]$num = "123" # 123 [string]$txt = 123 # "123" [array]$arr = "hello" # ("hello") [datetime]$dt = "2024-01-01" # DateTime 对象 # 隐式转换 $result = $a + $b # 数字加法 $count = $arr.Count # 数组计数二、常用运算符
1. 赋值运算符
$a = 5 # 普通赋值 $a += 3 # a = a + 3 $a -= 2 # a = a - 2 $a *= 4 # a = a * 4 $a /= 2 # a = a / 2 $a %= 3 # a = a % 3 (取余)2. 比较运算符
| 运算符 | 说明 | 示例 |
|---|---|---|
-eq | 等于 | $x -eq 5 |
-ne | 不等于 | $x -ne 5 |
-gt | 大于 | $x -gt 5 |
-lt | 小于 | $x -lt 5 |
-ge | 大于等于 | $x -ge 5 |
-le | 小于等于 | $x -le 5 |
-like | 通配匹配 | $str -like "abc*" |
-match | 正则匹配 | $str -match '\d+' |
-in | 在列表中 | 5 -in @(1,2,3,5,7) |
3. 逻辑运算符
# 与或非 if ($a -and $b) { ... } # 且 if ($a -or $b) { ... } # 或 if (-not $a) { ... } # 非 # 短路求值 ($false -and (Write-Host "这个不会执行")) # 不会打印4. 集合运算符
@(1,2,3) -contains 2 # true - 包含 @(1,2,3) -notcontains 4 # true - 不包含 @(1,2) -eq @(2,1) # false - 顺序不同 $(1,2,3) + $(4,5,6) # @(1,2,3,4,5,6) - 合并 $(1,2,3) -intersect $(2,3,4) # @(2,3) - 交集 $(1,2,3) -union @(3,4,5) # @(1,2,3,4,5) - 并集 $(1,2,3) -diff @(2,3,4) # @(1) - 差集三、流程控制语句
1. If 条件判断
# 基本 if-else if ($score -ge 60) { Write-Host "及格" } else { Write-Host "不及格" } # if-elseif-else if ($score -ge 90) { Write-Host "优秀" -ForegroundColor Green } elseif ($score -ge 80) { Write-Host "良好" -ForegroundColor Cyan } elseif ($score -ge 60) { Write-Host "及格" } else { Write-Host "不及格" } # Switch 多分支(类似 switch-case) switch ($day) { 1 { Write-Host "周一" } 2 { Write-Host "周二" } 3 { Write-Host "周三" } default { Write-Host "其他" } } # Switch with patterns switch ($city) { "/^[A-Z]/" { Write-Host "以大写开头" } "*北京*" { Write-Host "包含北京" } default { Write-Host "其他城市" } }2. For 循环
# 基本 for 循环 for ($i = 0; $i -lt 10; $i++) { Write-Host "$i" } # 数组索引遍历 $colors = @("红","绿","蓝") for ($i = 0; $i -lt $colors.Count; $i++) { Write-Host "${colors[$i]}-$i" } # foreach 迭代元素 foreach ($color in $colors) { Write-Host $color } # foreach with index $i = 0 foreach ($color in $colors) { Write-Host "$($color)-Index:$i" $i++ }3. While 和 Do-While
# while 循环 $i = 0 while ($i -lt 5) { Write-Host $i $i++ } # do-while 至少执行一次 do { $input = Read-Host "输入y继续" $result = $input.ToLower() } while ($result -ne "n") # foreach 内中断 $i = 0 foreach ($item in 1..100) { if ($item -eq 5) { break # 跳出循环 } Write-Host $item } # continue 跳过本次 for ($i = 1; $i -le 10; $i++) { if ($i % 2 -eq 0) { continue # 跳过偶数 } Write-Host $i # 只输出奇数 }4. 范围操作符
1..5 # @(1,2,3,4,5) 'a'..'e' # @('a','b','c','d','e') 2,4..10 # @(2,4,5,6,7,8,9,10) # 步进 1..10:2 # @(1,3,5,7,9) 1..10:-1 # @(10,9,8,7,6,5,4,3,2,1) # 选择特定项 (1..100)[0..5], (1..100)[-3]四、函数定义与调用
1. 基本函数
function Say-Hello { param([string]$Name) Write-Host "你好,$Name!" } Say-Hello "小明" Say-Hello2. 带返回值的函数
function Add-Numbers { param([int]$a, [int]$b) return $a + $b } $result = Add-Numbers 3 5 Write-Host "$result" # 8 # 简写返回 function Square { param([int]$x) $x * $x # 最后一行自动返回 }3. 高级函数特性
function Get-Summary { <# .SYNOPSIS 获取系统摘要 .DESCRIPTION 返回 CPU 和内存信息 .PARAMETER ShowDetails 是否显示详细信息 #> [CmdletBinding()] param( [Parameter(Mandatory=$false)] [switch]$Verbose, [ValidateRange(0,100)] [int]$Percent = 50 ) if ($Verbose) { Write-Verbose "详细模式已开启" } Write-Output "[System Info]" Write-Output "CPU Usage: $Percent%" return $true } # 调用 Get-Summary -Verbose Get-Summary -Verbose -Percent 80 Get-Summary -WhatIf # 测试不实际执行4. 全局/私有限定词
function global:Get-GlobalVar { return $script:globalValue } function private:HiddenFunc { # 只能在当前模块使用 }五、管道和操作符
1. 管道传递
# 管道 | 发送前对象的属性 Get-Service | Format-Table Name, Status # Where-Object 过滤 Get-Service | Where-Object {$_.Status -eq 'Running'} # Select-Object 选择属性 Get-Process | Select-Object Name, Id, CPU # Sort-Object 排序 Get-Service | Sort-Object Status # Group-Object 分组 Get-Service | Group-Object Status # Measure-Object 统计 (Get-Process).Count # 进程数量 Measure-Object -Property CPU -InputObject (Get-Process) | Select-Object Sum2. 特殊操作符
# 追加管道对象 Get-Service | Where-Object { $_.Status -eq 'Running' } | Select-Object -First 5 | Sort-Object StartTime # 分号分隔多个命令 Get-Date ; Get-Service ; Clear-Host # 反引号跨行 $output = Get-Content file.txt | Where-Object { $_ -match 'error' } | Out-File errors.txt # Tee-Object 同时保存到变量和管道 $content = Get-Content data.txt | Tee-Object -Variable lines | Where-Object { $_ -notlike '#*' }3. 管道重定向
# 标准重定向 Command > output.txt # 覆盖输出到文件 Command >> output.txt # 追加输出 Command 2> error.txt # 重定向错误流 # 按级别 Command > all.txt 2>&1 # 合并标准和错误到同一文件六、数组和哈希表
1. 数组操作
# 创建数组 $arr = 1, 2, 3 # 简单方式 $arr = @(1, 2, 3) # 明确数组 $arr = New-Object int[] 5 # 指定类型 # 添加元素 $arr += 4 # 追加 $arr = $arr + @("a", "b") # 合并 # 访问元素 $arr[0] # 第一个 $arr[-1] # 最后一个 $arr[0..2] # 切片 $arr[1,3,5] # 多选索引 # 删除元素 $arr = $arr.Where{$_ -ne 2} # PowerShell 5.1+ # 查询 $arr.Contains(3) # 是否包含 $arr.IndexOf(3) # 查找位置 $arr -gt 2 # 条件筛选2. 哈希表操作
# 创建哈希表 $person = @{ Name = "张三" Age = 25 City = "北京" Skills = @("HTML", "CSS", "JS") } # 添加/修改 $person.Email = "zhang@example.com" $person.Age = 26 # 访问 $person["Name"] # 通过键访问 $person.Name # 直接属性访问 # 删除 $person.Remove("City") # 遍历 foreach ($key in $person.Keys) { Write-Host "$key: $($person[$key])" } # 转换为对象 $personObj = New-Object PSObject -Property $person # 深度比较 Compare-Object $obj1 $obj2七、错误处理
1. Try-Catch-Finally
try { Get-Content "nonexistent.txt" # 如果出错,后续代码不执行 } catch [System.IO.FileNotFoundException] { Write-Host "文件未找到: $($_.Exception.Message)" -ForegroundColor Red } catch { Write-Host "发生错误: $($_.Exception.Message)" } finally { Write-Host "清理操作..." }2. 错误管理参数
# ErrorAction 参数 Get-Content file.txt -ErrorAction SilentlyContinue # 静默失败 Get-Content file.txt -ErrorAction Stop # 抛出异常 Get-Content file.txt -ErrorAction Continue # 继续执行 # InAllScope 作用域 $ErrorActionPreference = "Stop" # 全局设置3. 警告和调试信息
Write-Warning "这是一个警告" -ForegroundColor Yellow Write-Information "这是信息" -InformationAction Continue Write-Debug "调试信息" -Debug # 需 -Debug 标志 Write-Verbose "详细日志" -Verbose # 需 -Verbose 标志 # 捕获详细信息 $lastError = $error[0].Exception.Message八、模块和别名
1. 模块管理
# 查看所有已加载模块 Get-Module -ListAvailable # 导入模块 Import-Module Az # Azure Import-Module ActiveDirectory # AD Import-Module *.psm1 # 当前目录 # 导出模块 Export-ModuleMember -Function Get-MyFunc # 查看帮助 Get-Help about_modules2. 常用内置命令别名
| 别名 | 完整命令 | 说明 |
|---|---|---|
gci | Get-ChildItem | 列出目录内容 |
ls | Get-ChildItem | 列表 |
cd | Set-Location | 切换目录 |
pwd | Get-Location | 当前路径 |
cl | Clear-Host | 清屏 |
np | New-PSDrive | 新建驱动器 |
cp | Copy-Item | 复制 |
mv | Move-Item | 移动 |
rm | Remove-Item | 删除 |
mi | Microsoft.PowerShell.Management | PS 模块缩写 |
3. 创建自定义别名
Set-Alias getall Get-Content -Option AllScope # 查看别名 Get-Alias | Select-Object Definition, Command # 删除别名 Unregister-Alias aliasname九、环境配置和 Profile
1. Profile 文件
# 查看所有 profile 路径 $PROFILE # 编辑自动启动脚本 notepad $PROFILE.CurrentUserAllHosts2. 常用 Profile 配置
# 设置主题色 $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8' # 加载个人模块 Import-Module ~/Documents/PowerShell/Modules/MyUtils.psm1 # 设置默认执行策略 Set-ExecutionPolicy RemoteSigned -Scope CurrentUser十、实用完整示例
示例 1: 系统状态报告脚本
function Get-SystemReport { [CmdletBinding()] param( [switch]$Detailed ) Write-Output "=" * 50 Write-Output "系统状态报告 - $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))" Write-Output "=" * 50 Write-Output "`n【操作系统】" $osInfo = Get-CimInstance Win32_OperatingSystem Write-Output "名称: $($osInfo.Caption)" Write-Output "版本: $($osInfo.Version)" Write-Output "`n【处理器信息】" $cpu = Get-CimInstance Win32_Processor Write-Output "核心数: $($cpu.NumberOfCores)" Write-Output "逻辑处理器: $($cpu.NumberOfLogicalProcessors)" if ($Detailed) { Write-Output "`n【正在运行的服务】" Get-Service | Select-Object Name, Status, StartType | Format-Table -AutoSize Write-Output "`n【磁盘使用情况】" Get-CimInstance Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3} | Select-Object DeviceID, @{Name='Size';Expression={[math]::Round($_.Size/1GB,2)}}, @{Name='FreeSpace';Expression={[math]::Round($_.FreeSpace/1GB,2)}} | Format-Table -AutoSize } Write-Output "`n【结束】" Write-Output "=" * 50 } # 运行 Get-SystemReport -Detailed示例 2: 批量文件搜索工具
function Find-InFiles { <# .SYNOPSIS 递归搜索文件内容 .PARAMETER Directory 搜索目录 .PARAMETER Pattern 搜索模式 .PARAMETER Include 文件名模式 #> [CmdletBinding()] param( [string]$Path = ".", [string]$Pattern, [string]$Include = "*" ) if (-not (Test-Path $Path)) { throw "目录不存在: $Path" } if ([string]::IsNullOrWhiteSpace($Pattern)) { throw "需要提供搜索模式" } Get-ChildItem -Path $Path -Recurse -Filter $Include -File | Where-Object { $_.Length -lt 1MB } | # 避免大文件 Select-Object -First 100 | # 性能保护 ForEach-Object { try { $lines = Select-String -Path $_.FullName -Pattern $Pattern -Context 1,2 | Select-Object -ExpandProperty LineNumber if ($lines) { Write-Output "=== $($_.FullName) ===" foreach ($line in $lines) { Write-Output " Line $line: $((Select-String -Path $_.FullName -Pattern $Pattern -SimpleMatch).Line.Trim())" } } } catch { Write-Warning "无法读取: $($_.FullName)" } } } # 使用 Find-InFiles -Path ".\src" -Pattern "TODO" -Include "*.ps1"示例 3: 数据转换工具
function Convert-ToCSV { param( [Array]$InputObject, [string]$OutputPath ) $InputObject | Export-Csv -Path $OutputPath -NoTypeInformation Write-Output "已导出 $($_.Count) 条记录到 $OutputPath" } function Import-FromCSV { param( [string]$Path ) $data = Import-Csv -Path $Path Write-Output "共加载 $($data.Count) 条数据" # 返回对象供进一步处理 return $data } # 使用示例 $processes = Get-Process | Select-Object Name, Id, WorkingSet | Sort-Object WorkingSet -Descending | Select-Object -First 10 Convert-ToCSV -InputObject $processes -OutputPath "processes.csv" $newData = Import-FromCSV -Path "processes.csv"十一、快速参考表
| 类别 | 常用命令 |
|---|---|
| 文件操作 | Get-ChildItem, Copy-Item, Move-Item, Remove-Item, Test-Path |
| 系统管理 | Get-Service, Get-Process, Get-EventLog, Restart-Computer |
| 网络 | Invoke-RestMethod, Invoke-WebRequest, Test-NetConnection |
| 对象处理 | Where-Object, Select-Object, Sort-Object, Group-Object |
| 文本处理 | Get-Content, Set-Content, Out-File, Select-String |
| 注册表 | Get-ChildItem HKLM:, New-ItemProperty |
| 权限 | Get-Acl, Set-Acl, Grant-Access |
十二、最佳实践建议
✅推荐使用:
- 使用
param()明确定义函数参数 - 使用
-WhatIf测试危险命令 - 使用
try-catch处理可能失败的操做 - 使用
Write-Output显式返回值 - 遵循
动词-名词命名规范
❌避免:
- 硬编码文件路径
- 直接使用绝对路径
- 忽略错误处理
- 过度使用
break嵌套 - 在循环中重复构建对象
掌握这些基础语法后,你就可以高效地使用 PowerShell 进行各种自动化任务了!如需深入了解某个特定领域(如 Active Directory、Azure、SQL Server 等),可以继续提问。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄
💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍
🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙