PowerShell 技能连载 - AI 智能脚本生成引擎优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Invoke-AIScriptGeneration {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$NaturalLanguageQuery,

[ValidateRange(1,5)]
[int]$MaxAttempts = 3
)

$codeReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
GeneratedScript = $null
ValidationErrors = @()
OptimizationLevel = 0
}

try {
$prompt = @"
作为PowerShell专家,请将以下运维需求转换为安全可靠的代码:
需求:$NaturalLanguageQuery
要求:
1. 包含try/catch错误处理
2. 支持WhatIf预执行模式
3. 输出结构化对象
4. 符合PowerShell最佳实践
"@

# 调用OpenAI API
$response = Invoke-RestMethod -Uri 'https://api.openai.com/v1/chat/completions' \
-Headers @{ Authorization = "Bearer $env:OPENAI_API_KEY" } \
-Body (@{
model = "gpt-4-turbo"
messages = @(@{ role = "user"; content = $prompt })
temperature = 0.2
max_tokens = 1500
} | ConvertTo-Json)

# 代码安全验证
$validationResults = $response.choices[0].message.content |
Where-Object { $_ -notmatch 'Remove-Item|Format-Table' } |
Test-ScriptAnalyzer -Severity Error

$codeReport.GeneratedScript = $response.choices[0].message.content
$codeReport.ValidationErrors = $validationResults
$codeReport.OptimizationLevel = (100 - ($validationResults.Count * 20))
}
catch {
Write-Error "AI脚本生成失败: $_"
if ($MaxAttempts -gt 1) {
return Invoke-AIScriptGeneration -NaturalLanguageQuery $NaturalLanguageQuery -MaxAttempts ($MaxAttempts - 1)
}
}

# 生成智能编码报告
$codeReport | Export-Csv -Path "$env:TEMP/AIScriptReport_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
return $codeReport
}

核心功能

  1. 自然语言到代码的智能转换
  2. 生成代码的安全验证
  3. 多轮重试机制
  4. 代码优化评分系统

应用场景

  • 运维需求快速原型开发
  • 新手脚本编写辅助
  • 跨团队需求标准化
  • 自动化脚本知识库构建

PowerShell PSProvider深度解析

内存驱动器实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$provider = New-Object Management.Automation.ProviderInfo(
@([Management.Automation.Provider.CmdletProvider]),
"MemoryProvider",
[Microsoft.PowerShell.Commands.FileSystemProvider],
"",
"",
$null
)

$ctx = New-Object Management.Automation.ProviderContext($provider)
$drive = New-Object Management.Automation.PSDriveInfo(
"mem",
$provider,
"",
"内存驱动器",
$null
)

# 创建虚拟文件
New-Item -Path 'mem:\config.json' -ItemType File -Value @"
{
"settings": {
"cacheSize": 1024
}
}
"@

项操作重载技术

1
2
3
4
5
6
7
8
9
10
class CustomProvider : NavigationCmdletProvider {
[void] NewItem(string path, string type, object content) {
base.NewItem(path, "Directory", "特殊项")
[MemoryStore]::Add(path, content)
}

[object] GetItem(string path) {
return [MemoryStore]::Get(path)
}
}

应用场景

  1. 配置中心虚拟文件系统
  2. 加密存储透明访问层
  3. 跨平台路径统一抽象
  4. 内存数据库交互界面

开发注意事项

  • 实现必要生命周期方法
  • 处理并发访问锁机制
  • 维护项状态元数据
  • 支持管道流式操作

PowerShell 技能连载 - 无服务器环境下的零信任检测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function Invoke-ServerlessHealthCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroup
)

# 获取函数应用运行环境信息
$context = Get-AzContext
$functions = Get-AzFunctionApp -ResourceGroupName $ResourceGroup

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
FunctionApps = @()
SecurityFindings = @()
}

# 检查TLS版本配置
$functions | ForEach-Object {
$config = Get-AzFunctionAppSetting -Name $_.Name -ResourceGroupName $ResourceGroup

$appReport = [PSCustomObject]@{
AppName = $_.Name
RuntimeVersion = $_.Config.NetFrameworkVersion
HTTPSOnly = $_.Config.HttpsOnly
MinTLSVersion = $config['minTlsVersion']
}
$report.FunctionApps += $appReport

if ($appReport.MinTLSVersion -lt '1.2') {
$report.SecurityFindings += [PSCustomObject]@{
Severity = 'High'
Description = "函数应用 $($_.Name) 使用不安全的TLS版本: $($appReport.MinTLSVersion)"
Recommendation = '在应用设置中将minTlsVersion更新为1.2'
}
}
}

# 生成安全报告
$report | Export-Clixml -Path "$env:TEMP/ServerlessSecurityReport_$(Get-Date -Format yyyyMMdd).xml"
return $report
}

核心功能

  1. Azure Functions运行环境自动检测
  2. TLS安全配置合规检查
  3. 零信任架构下的安全基线验证
  4. 自动化XML报告生成

典型应用场景

  • 无服务器架构安全审计
  • 云环境合规自动化核查
  • 持续安全监控(CSM)实现
  • DevOps流水线安全卡点集成

自动化零信任设备健康检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function Get-DeviceCompliance {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ComputerName
)

# 验证TPM状态
$tpmStatus = Get-Tpm -ComputerName $ComputerName -ErrorAction SilentlyContinue
# 检查BitLocker加密状态
$bitlocker = Get-BitLockerVolume -MountPoint $env:SystemDrive -ErrorAction SilentlyContinue
# 获取防病毒状态
$avStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue

[PSCustomObject]@{
ComputerName = $ComputerName
TPMEnabled = $tpmStatus.TpmPresent
SecureBoot = (Confirm-SecureBootUEFI).SecureBootEnabled
BitLockerStatus = $bitlocker.VolumeStatus
AntivirusEnabled = $avStatus.AMServiceEnabled
LastUpdate = (Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1).InstalledOn
}
}

# 执行企业终端健康检查
$devices = 'PC001','PC002','PC003'
$report = $devices | ForEach-Object {
Get-DeviceCompliance -ComputerName $_ -Verbose
}

# 生成合规性报告
$report | Export-Csv -Path "ZeroTrust_Compliance_Report_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation

本脚本实现以下零信任核心检查项:

  1. TPM芯片启用状态验证
  2. Secure Boot安全启动配置
  3. 系统盘BitLocker加密状态
  4. 防病毒实时监控状态
  5. 系统最后更新日期

扩展建议:

  • 与Azure AD条件访问策略集成
  • 添加自动修复功能
  • 实现实时监控告警机制

PowerShell 技能连载 - 安全策略配置指南

PowerShell执行策略是脚本安全的第一道防线,通过灵活配置平衡功能与安全。

1
2
3
4
5
# 查看当前执行策略
Get-ExecutionPolicy -List

# 设置远程签名策略
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

脚本签名验证

  1. 创建代码签名证书:

    1
    2
    3
    4
    5
    6
    7
    $certParams = @{
    Subject = 'CN=PowerShell Scripts'
    Type = 'CodeSigning'
    KeyUsage = 'DigitalSignature'
    KeyLength = 2048
    }
    $cert = New-SelfSignedCertificate @certParams
  2. 签名脚本文件:

    1
    2
    3
    4
    5
    6
    $signParams = @{
    Certificate = $cert
    FilePath = 'script.ps1'
    TimestampServer = 'http://timestamp.digicert.com'
    }
    Set-AuthenticodeSignature @signParams

安全日志分析

1
2
3
4
5
6
7
# 查询脚本块日志
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-PowerShell/Operational'
Id = 4104
} | Where-Object {
$_.Message -match '可疑命令'
}

最佳实践:

  • 使用AllSigned策略生产环境
  • 定期轮换签名证书
  • 启用脚本块日志记录
  • 结合AppLocker增强控制

PowerShell 技能连载 - 红队渗透测试自动化框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function Invoke-RedTeamScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$TargetRange,

[ValidateSet('Basic','Advanced')]
[string]$ScanMode = 'Basic'
)

$threatReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
VulnerableSystems = @()
AttackPaths = @()
RiskScore = 0
}

try {
# 检测本地权限提升漏洞
$localVulns = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall |
Where-Object { $_.GetValue('DisplayName') -match '脆弱服务' }
if ($localVulns) {
$threatReport.VulnerableSystems += [PSCustomObject]@{
SystemName = $env:COMPUTERNAME
Vulnerability = '本地权限提升'
CVE = 'CVE-2024-XXXX'
}
}

# 高级模式横向移动检测
if ($ScanMode -eq 'Advanced') {
$networkSystems = Test-NetConnection -ComputerName $TargetRange -Port 445 |
Where-Object TcpTestSucceeded

$networkSystems | ForEach-Object {
$shares = Get-SmbShare -ComputerName $_.RemoteAddress -ErrorAction SilentlyContinue
if ($shares) {
$threatReport.AttackPaths += [PSCustomObject]@{
Source = $env:COMPUTERNAME
Target = $_.RemoteAddress
AttackVector = 'SMB共享漏洞'
}
}
}
}

# 计算风险评分
$threatReport.RiskScore = [math]::Min(100, ($threatReport.VulnerableSystems.Count * 30) + ($threatReport.AttackPaths.Count * 20))
}
catch {
Write-Error "渗透测试失败: $_"
}

# 生成红队行动报告
$threatReport | ConvertTo-Json | Out-File -Path "$env:TEMP/RedTeamReport_$(Get-Date -Format yyyyMMdd).json"
return $threatReport
}

核心功能

  1. 本地权限提升漏洞检测
  2. 网络横向移动路径分析
  3. SMB共享漏洞自动化扫描
  4. 动态风险评分系统

应用场景

  • 红队渗透测试演练
  • 企业网络安全评估
  • 攻击路径可视化
  • 安全防御策略验证

PowerShell 技能连载 - CSV 数据处理技巧

在 PowerShell 中处理 CSV 数据是一项常见任务,特别是在处理报表、数据导入导出时。本文将介绍一些实用的 CSV 处理技巧。

首先,让我们看看如何创建和读取 CSV 数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 创建示例 CSV 数据
$csvData = @"
姓名,年龄,部门,职位,入职日期
张三,30,技术部,高级工程师,2020-01-15
李四,28,市场部,市场经理,2019-06-20
王五,35,财务部,财务主管,2018-03-10
赵六,32,人力资源部,HR专员,2021-09-05
"@

# 将 CSV 字符串保存到文件
$csvData | Out-File -FilePath "employees.csv" -Encoding UTF8

# 读取 CSV 文件
$employees = Import-Csv -Path "employees.csv" -Encoding UTF8

# 显示数据
Write-Host "员工列表:"
$employees | Format-Table

处理带有特殊字符的 CSV:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 创建包含特殊字符的 CSV
$specialCsv = @"
产品名称,价格,描述,备注
"笔记本电脑",5999,"高性能,轻薄便携","支持""快速充电"""
"无线鼠标",199,"人体工学,静音","包含""电池"""
"机械键盘",899,"RGB背光,青轴","支持""宏编程"""
"@

# 使用引号处理特殊字符
$specialCsv | Out-File -FilePath "products.csv" -Encoding UTF8

# 读取并处理特殊字符
$products = Import-Csv -Path "products.csv" -Encoding UTF8
Write-Host "`n产品列表:"
$products | Format-Table

使用自定义分隔符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建使用分号分隔的 CSV
$semicolonCsv = @"
姓名;年龄;部门;职位
张三;30;技术部;高级工程师
李四;28;市场部;市场经理
王五;35;财务部;财务主管
"@

$semicolonCsv | Out-File -FilePath "employees_semicolon.csv" -Encoding UTF8

# 使用自定义分隔符读取
$employees = Import-Csv -Path "employees_semicolon.csv" -Delimiter ";" -Encoding UTF8
Write-Host "`n使用分号分隔的员工列表:"
$employees | Format-Table

数据过滤和转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 读取 CSV 并进行数据过滤
$employees = Import-Csv -Path "employees.csv" -Encoding UTF8

# 过滤特定部门的员工
$techDept = $employees | Where-Object { $_.部门 -eq "技术部" }
Write-Host "`n技术部员工:"
$techDept | Format-Table

# 转换数据格式
$employees | ForEach-Object {
[PSCustomObject]@{
姓名 = $_.姓名
年龄 = [int]$_.年龄
部门 = $_.部门
职位 = $_.职位
入职日期 = [datetime]$_.入职日期
工作年限 = ((Get-Date) - [datetime]$_.入职日期).Days / 365
}
} | Export-Csv -Path "employees_processed.csv" -NoTypeInformation -Encoding UTF8

一些实用的 CSV 处理技巧:

  1. 处理大文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 使用流式处理大型 CSV 文件
    $reader = [System.IO.StreamReader]::new("large-data.csv")
    $header = $reader.ReadLine().Split(",")
    while (-not $reader.EndOfStream) {
    $line = $reader.ReadLine().Split(",")
    $record = @{}
    for ($i = 0; $i -lt $header.Count; $i++) {
    $record[$header[$i]] = $line[$i]
    }
    [PSCustomObject]$record
    }
    $reader.Close()
  2. 数据验证:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    function Test-CsvFormat {
    param(
    [string]$CsvPath,
    [string[]]$RequiredColumns
    )

    $csv = Import-Csv -Path $CsvPath -Encoding UTF8
    $headers = $csv[0].PSObject.Properties.Name

    foreach ($column in $RequiredColumns) {
    if ($column -notin $headers) {
    return $false
    }
    }
    return $true
    }
  3. 合并多个 CSV 文件:

1
2
3
4
5
6
7
# 合并多个 CSV 文件
$csvFiles = Get-ChildItem -Path "*.csv" -Filter "employees_*.csv"
$allEmployees = @()
foreach ($file in $csvFiles) {
$allEmployees += Import-Csv -Path $file.FullName -Encoding UTF8
}
$allEmployees | Export-Csv -Path "all_employees.csv" -NoTypeInformation -Encoding UTF8

这些技巧将帮助您更有效地处理 CSV 数据。记住,在处理大型 CSV 文件时,考虑使用流式处理方法来优化内存使用。同时,始终注意数据的完整性和格式的正确性。

PowerShell 技能连载 - 元宇宙虚拟环境自动化管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function Invoke-MetaverseDeployment {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$EnvironmentBlueprint,

[ValidateRange(1,100)]
[int]$NodeCount = 5
)

$deploymentReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
EnvironmentID = (New-Guid).Guid
AllocatedResources = @()
PerformanceMetrics = @()
}

# 虚拟节点资源配置
1..$NodeCount | ForEach-Object {
$nodeConfig = [PSCustomObject]@{
NodeID = "VNODE-$((Get-Date).ToString('HHmmssfff'))"
CPU = 4
Memory = '16GB'
Storage = '500GB SSD'
NetworkLatency = (Get-Random -Minimum 2 -Maximum 15)
}
$deploymentReport.AllocatedResources += $nodeConfig
}

# 虚拟环境健康检查
$deploymentReport.AllocatedResources | ForEach-Object {
$metrics = [PSCustomObject]@{
NodeID = $_.NodeID
Throughput = (Get-Random -Minimum 100 -Maximum 1000)
PacketLoss = (Get-Random -Minimum 0.1 -Maximum 5.0)
AvatarCapacity = (Get-Random -Minimum 50 -Maximum 200)
}
$deploymentReport.PerformanceMetrics += $metrics
}

# 生成三维可视化报告
$reportPath = "$env:TEMP/MetaverseReport_$(Get-Date -Format yyyyMMdd).glb"
$deploymentReport | ConvertTo-Json -Depth 5 |
Out-File -Path $reportPath -Encoding UTF8
return $deploymentReport
}

核心功能

  1. 分布式虚拟节点自动配置
  2. 网络延迟模拟与容量规划
  3. 实时三维性能指标采集
  4. GLB格式可视化报告

应用场景

  • 元宇宙基础架构部署
  • 虚拟演唱会资源调度
  • 数字孪生工厂监控
  • 虚拟现实教育资源分配

PowerShell 技能连载 - 零信任架构下的设备健康检查自动化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function Invoke-DeviceHealthCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$DeviceName,

[ValidateSet('Basic','Full')]
[string]$ScanMode = 'Basic'
)

$complianceReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
DeviceName = $DeviceName
EncryptionStatus = $null
PatchLevel = $null
FirewallRules = @()
ComplianceScore = 0
}

try {
# 验证BitLocker加密状态
$encryptionStatus = Get-BitLockerVolume -MountPoint C: |
Select-Object -ExpandProperty EncryptionPercentage
$complianceReport.EncryptionStatus = $encryptionStatus -ge 100 ? 'Compliant' : 'Non-Compliant'

# 检查系统更新状态
$updates = Get-HotFix |
Where-Object InstalledOn -lt (Get-Date).AddDays(-30)
$complianceReport.PatchLevel = $updates.Count -eq 0 ? 'Current' : 'Outdated'

# 审计防火墙规则(完整扫描模式)
if ($ScanMode -eq 'Full') {
$firewallRules = Get-NetFirewallRule |
Where-Object Enabled -eq True |
Select-Object DisplayName, Direction, Action
$complianceReport.FirewallRules = $firewallRules
}

# 计算合规分数
$score = 0
if ($complianceReport.EncryptionStatus -eq 'Compliant') { $score += 40 }
if ($complianceReport.PatchLevel -eq 'Current') { $score += 30 }
if ($complianceReport.FirewallRules.Count -eq 0) { $score += 30 }
$complianceReport.ComplianceScore = $score
}
catch {
Write-Error "设备健康检查失败: $_"
}

# 生成零信任合规报告
$complianceReport | Export-Clixml -Path "$env:TEMP/${DeviceName}_ComplianceReport_$(Get-Date -Format yyyyMMdd).xml"
return $complianceReport
}

核心功能

  1. 自动化BitLocker加密状态验证
  2. 系统补丁级别智能评估
  3. 防火墙规则深度审计(完整扫描模式)
  4. 动态合规评分系统

应用场景

  • 零信任安全架构实施
  • 终端设备合规自动化审计
  • 安全基线动态验证
  • 监管合规报告生成

PowerShell变量作用域深度解析

作用域层级解析

1
2
3
4
5
6
7
8
9
# 全局作用域示例
$global:config = 'Server1'

function Show-Config {
# 局部作用域
$local:connection = 'Active'
"$global:config - $local:connection"
}
Show-Config

作用域修饰符实战

1
2
3
4
5
6
7
8
# 跨作用域访问
function Set-Cache {
$script:cache = @{}
$cache.Add('timestamp', (Get-Date))
}

Set-Cache
$script:cache.Values

注意事项

  1. 使用$private:限制变量可见范围
  2. 通过Get-Variable -Scope查看不同作用域变量
  3. 避免在函数内意外修改全局变量
  4. 嵌套函数中的变量继承规则