PowerShell 技能连载 - 图像处理技巧

在 PowerShell 中处理图像文件可能不是最常见的任务,但在某些场景下非常有用。本文将介绍一些实用的图像处理技巧。

首先,让我们看看基本的图像操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 创建图像处理函数
function Get-ImageInfo {
param(
[string]$ImagePath
)

# 使用 System.Drawing 获取图像信息
Add-Type -AssemblyName System.Drawing
$image = [System.Drawing.Image]::FromFile($ImagePath)

$info = [PSCustomObject]@{
FileName = Split-Path $ImagePath -Leaf
Width = $image.Width
Height = $image.Height
PixelFormat = $image.PixelFormat
Resolution = $image.HorizontalResolution
FileSize = (Get-Item $ImagePath).Length
}

$image.Dispose()
return $info
}

图像格式转换:

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
# 创建图像格式转换函数
function Convert-ImageFormat {
param(
[string]$InputPath,
[string]$OutputPath,
[ValidateSet("jpg", "png", "bmp", "gif")]
[string]$TargetFormat
)

try {
Add-Type -AssemblyName System.Drawing
$image = [System.Drawing.Image]::FromFile($InputPath)

switch ($TargetFormat) {
"jpg" { $image.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Jpeg) }
"png" { $image.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Png) }
"bmp" { $image.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Bmp) }
"gif" { $image.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Gif) }
}

$image.Dispose()
Write-Host "图像转换完成:$OutputPath"
}
catch {
Write-Host "转换失败:$_"
}
}

图像调整:

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
# 创建图像调整函数
function Resize-Image {
param(
[string]$InputPath,
[string]$OutputPath,
[int]$Width,
[int]$Height
)

try {
Add-Type -AssemblyName System.Drawing
$image = [System.Drawing.Image]::FromFile($InputPath)

# 创建新的位图
$newImage = New-Object System.Drawing.Bitmap($Width, $Height)
$graphics = [System.Drawing.Graphics]::FromImage($newImage)

# 设置高质量插值模式
$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic

# 绘制调整后的图像
$graphics.DrawImage($image, 0, 0, $Width, $Height)

# 保存结果
$newImage.Save($OutputPath)

# 清理资源
$graphics.Dispose()
$newImage.Dispose()
$image.Dispose()

Write-Host "图像调整完成:$OutputPath"
}
catch {
Write-Host "调整失败:$_"
}
}

图像效果处理:

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
# 创建图像效果处理函数
function Apply-ImageEffect {
param(
[string]$InputPath,
[string]$OutputPath,
[ValidateSet("grayscale", "sepia", "blur", "sharpen")]
[string]$Effect
)

try {
Add-Type -AssemblyName System.Drawing
$image = [System.Drawing.Image]::FromFile($InputPath)
$bitmap = New-Object System.Drawing.Bitmap($image)

switch ($Effect) {
"grayscale" {
for ($x = 0; $x -lt $bitmap.Width; $x++) {
for ($y = 0; $y -lt $bitmap.Height; $y++) {
$pixel = $bitmap.GetPixel($x, $y)
$gray = [int](($pixel.R * 0.3) + ($pixel.G * 0.59) + ($pixel.B * 0.11))
$bitmap.SetPixel($x, $y, [System.Drawing.Color]::FromArgb($gray, $gray, $gray))
}
}
}
"sepia" {
for ($x = 0; $x -lt $bitmap.Width; $x++) {
for ($y = 0; $y -lt $bitmap.Height; $y++) {
$pixel = $bitmap.GetPixel($x, $y)
$r = [int](($pixel.R * 0.393) + ($pixel.G * 0.769) + ($pixel.B * 0.189))
$g = [int](($pixel.R * 0.349) + ($pixel.G * 0.686) + ($pixel.B * 0.168))
$b = [int](($pixel.R * 0.272) + ($pixel.G * 0.534) + ($pixel.B * 0.131))
$bitmap.SetPixel($x, $y, [System.Drawing.Color]::FromArgb($r, $g, $b))
}
}
}
}

$bitmap.Save($OutputPath)

# 清理资源
$bitmap.Dispose()
$image.Dispose()

Write-Host "已应用效果:$Effect"
}
catch {
Write-Host "效果处理失败:$_"
}
}

这些技巧将帮助您更有效地处理图像文件。记住,在处理图像时,始终要注意内存使用和资源释放。同时,建议在处理大型图像文件时使用流式处理方式,以提高性能。

PowerShell 技能连载 - 教育设备同步系统

在教育环境中,设备同步对于确保教学资源的统一性和可访问性至关重要。本文将介绍如何使用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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function Get-EducationDevices {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Location,

[Parameter()]
[string[]]$DeviceTypes,

[Parameter()]
[string]$Status,

[Parameter()]
[switch]$IncludeOffline
)

try {
$devices = [PSCustomObject]@{
Location = $Location
QueryTime = Get-Date
Devices = @()
}

# 从设备管理系统获取设备列表
$deviceList = Get-DeviceList -Location $Location `
-DeviceTypes $DeviceTypes `
-Status $Status

foreach ($device in $deviceList) {
$deviceInfo = [PSCustomObject]@{
DeviceID = $device.ID
Name = $device.Name
Type = $device.Type
Location = $device.Location
Status = $device.Status
LastSync = $device.LastSync
IPAddress = $device.IPAddress
MACAddress = $device.MACAddress
OSVersion = $device.OSVersion
Storage = Get-DeviceStorage -DeviceID $device.ID
Network = Get-DeviceNetwork -DeviceID $device.ID
}

# 检查设备在线状态
if ($IncludeOffline -or (Test-DeviceConnection -DeviceID $device.ID)) {
$devices.Devices += $deviceInfo
}
}

return $devices
}
catch {
Write-Error "获取教育设备列表失败:$_"
return $null
}
}

function Update-DeviceInventory {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Location,

[Parameter()]
[string]$InventoryPath,

[Parameter()]
[switch]$Force
)

try {
$inventory = [PSCustomObject]@{
Location = $Location
UpdateTime = Get-Date
Devices = @()
}

# 获取所有设备
$devices = Get-EducationDevices -Location $Location -IncludeOffline

# 更新设备清单
foreach ($device in $devices.Devices) {
$inventory.Devices += [PSCustomObject]@{
DeviceID = $device.DeviceID
Name = $device.Name
Type = $device.Type
Status = $device.Status
LastUpdate = Get-Date
HardwareInfo = Get-DeviceHardwareInfo -DeviceID $device.DeviceID
SoftwareInfo = Get-DeviceSoftwareInfo -DeviceID $device.DeviceID
MaintenanceHistory = Get-DeviceMaintenanceHistory -DeviceID $device.DeviceID
}
}

# 保存设备清单
if ($InventoryPath) {
$inventory | ConvertTo-Json -Depth 10 | Out-File -FilePath $InventoryPath -Force
}

return $inventory
}
catch {
Write-Error "更新设备清单失败:$_"
return $null
}
}

内容同步

接下来,创建一个用于同步教育内容的函数:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function Sync-EducationContent {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$DeviceID,

[Parameter(Mandatory = $true)]
[string[]]$ContentTypes,

[Parameter()]
[string]$SourcePath,

[Parameter()]
[string]$DestinationPath,

[Parameter()]
[switch]$Force,

[Parameter()]
[int]$RetryCount = 3
)

try {
$syncResult = [PSCustomObject]@{
DeviceID = $DeviceID
StartTime = Get-Date
ContentTypes = $ContentTypes
Status = "InProgress"
Details = @()
}

# 检查设备状态
$deviceStatus = Get-DeviceStatus -DeviceID $DeviceID
if (-not $deviceStatus.IsOnline) {
throw "设备 $DeviceID 当前处于离线状态"
}

# 检查存储空间
$storageStatus = Get-DeviceStorage -DeviceID $DeviceID
if (-not $storageStatus.HasEnoughSpace) {
throw "设备存储空间不足"
}

# 同步每种类型的内容
foreach ($contentType in $ContentTypes) {
$syncDetail = [PSCustomObject]@{
ContentType = $contentType
StartTime = Get-Date
Status = "InProgress"
Files = @()
}

try {
# 获取需要同步的文件列表
$files = Get-ContentFiles -ContentType $contentType `
-SourcePath $SourcePath `
-DeviceID $DeviceID

foreach ($file in $files) {
$retryCount = 0
$success = $false

while (-not $success -and $retryCount -lt $RetryCount) {
try {
$result = Copy-ContentFile -SourceFile $file.SourcePath `
-DestinationFile $file.DestinationPath `
-DeviceID $DeviceID

if ($result.Success) {
$success = $true
$syncDetail.Files += [PSCustomObject]@{
FileName = $file.FileName
Size = $file.Size
Status = "Success"
SyncTime = Get-Date
}
}
}
catch {
$retryCount++
if ($retryCount -eq $RetryCount) {
throw "文件同步失败:$_"
}
Start-Sleep -Seconds 2
}
}
}

$syncDetail.Status = "Success"
$syncDetail.EndTime = Get-Date
}
catch {
$syncDetail.Status = "Failed"
$syncDetail.Error = $_.Exception.Message
}

$syncResult.Details += $syncDetail
}

# 更新同步状态
$syncResult.Status = if ($syncResult.Details.Status -contains "Failed") { "Failed" } else { "Success" }
$syncResult.EndTime = Get-Date

return $syncResult
}
catch {
Write-Error "内容同步失败:$_"
return $null
}
}

状态监控

最后,创建一个用于监控教育设备状态的函数:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
function Monitor-DeviceStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Location,

[Parameter()]
[string[]]$DeviceTypes,

[Parameter()]
[int]$CheckInterval = 300,

[Parameter()]
[string]$LogPath,

[Parameter()]
[hashtable]$AlertThresholds
)

try {
$monitor = [PSCustomObject]@{
Location = $Location
StartTime = Get-Date
Devices = @()
Alerts = @()
}

while ($true) {
$checkTime = Get-Date
$devices = Get-EducationDevices -Location $Location -DeviceTypes $DeviceTypes

foreach ($device in $devices.Devices) {
$deviceStatus = [PSCustomObject]@{
DeviceID = $device.DeviceID
CheckTime = $checkTime
Status = $device.Status
Metrics = @{}
Alerts = @()
}

# 检查设备性能指标
$deviceStatus.Metrics = Get-DeviceMetrics -DeviceID $device.DeviceID

# 检查告警阈值
if ($AlertThresholds) {
foreach ($metric in $deviceStatus.Metrics.Keys) {
if ($AlertThresholds.ContainsKey($metric)) {
$threshold = $AlertThresholds[$metric]
$value = $deviceStatus.Metrics[$metric]

if ($value -gt $threshold.Max) {
$deviceStatus.Alerts += [PSCustomObject]@{
Type = "HighValue"
Metric = $metric
Value = $value
Threshold = $threshold.Max
Time = $checkTime
}
}

if ($value -lt $threshold.Min) {
$deviceStatus.Alerts += [PSCustomObject]@{
Type = "LowValue"
Metric = $metric
Value = $value
Threshold = $threshold.Min
Time = $checkTime
}
}
}
}
}

$monitor.Devices += $deviceStatus

# 处理告警
if ($deviceStatus.Alerts.Count -gt 0) {
foreach ($alert in $deviceStatus.Alerts) {
$monitor.Alerts += $alert

# 记录告警日志
if ($LogPath) {
$alert | ConvertTo-Json | Out-File -FilePath $LogPath -Append
}

# 发送告警通知
Send-DeviceAlert -Alert $alert
}
}
}

Start-Sleep -Seconds $CheckInterval
}

return $monitor
}
catch {
Write-Error "设备状态监控失败:$_"
return $null
}
}

使用示例

以下是如何使用这些函数来管理教育设备的示例:

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
# 配置设备监控参数
$monitorConfig = @{
Location = "教学楼A"
DeviceTypes = @("StudentPC", "TeacherPC", "Projector")
CheckInterval = 300
LogPath = "C:\Logs\device_status.json"
AlertThresholds = @{
"CPUUsage" = @{
Min = 0
Max = 90
}
"MemoryUsage" = @{
Min = 0
Max = 85
}
"DiskUsage" = @{
Min = 0
Max = 95
}
}
}

# 更新设备清单
$inventory = Update-DeviceInventory -Location $monitorConfig.Location `
-InventoryPath "C:\Inventory\devices.json" `
-Force

# 同步教育内容
$syncResult = Sync-EducationContent -DeviceID "PC001" `
-ContentTypes @("Courseware", "Assignments", "Resources") `
-SourcePath "\\Server\EducationContent" `
-DestinationPath "C:\Education" `
-RetryCount 3

# 启动设备状态监控
$monitor = Start-Job -ScriptBlock {
param($config)
Monitor-DeviceStatus -Location $config.Location `
-DeviceTypes $config.DeviceTypes `
-CheckInterval $config.CheckInterval `
-LogPath $config.LogPath `
-AlertThresholds $config.AlertThresholds
} -ArgumentList $monitorConfig

最佳实践

  1. 实现设备分组管理
  2. 使用增量同步提高效率
  3. 建立完整的备份机制
  4. 实施访问控制策略
  5. 定期进行系统维护
  6. 保持详细的同步日志
  7. 实现自动化的状态报告
  8. 建立应急响应机制

PowerShell 技能连载 - 网络操作技巧

在 PowerShell 中处理网络操作是一项常见任务,特别是在系统管理和自动化过程中。本文将介绍一些实用的网络操作技巧。

首先,让我们看看基本的网络连接测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 测试网络连接
$hosts = @(
"www.baidu.com",
"www.qq.com",
"www.taobao.com"
)

foreach ($host in $hosts) {
$result = Test-NetConnection -ComputerName $host -Port 80
Write-Host "`n测试 $host 的连接:"
Write-Host "是否可达:$($result.TcpTestSucceeded)"
Write-Host "响应时间:$($result.PingReplyDetails.RoundtripTime)ms"
}

获取网络配置信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 获取网络适配器信息
$adapters = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }

foreach ($adapter in $adapters) {
Write-Host "`n网卡名称:$($adapter.Name)"
Write-Host "连接状态:$($adapter.Status)"
Write-Host "MAC地址:$($adapter.MacAddress)"

# 获取IP配置
$ipConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.ifIndex
Write-Host "IP地址:$($ipConfig.IPv4Address.IPAddress)"
Write-Host "子网掩码:$($ipConfig.IPv4Address.PrefixLength)"
Write-Host "默认网关:$($ipConfig.IPv4DefaultGateway.NextHop)"
}

配置网络设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 配置静态IP地址
$adapterName = "以太网"
$ipAddress = "192.168.1.100"
$prefixLength = 24
$defaultGateway = "192.168.1.1"

# 获取网卡
$adapter = Get-NetAdapter -Name $adapterName

# 配置IP地址
New-NetIPAddress -InterfaceIndex $adapter.ifIndex -IPAddress $ipAddress -PrefixLength $prefixLength

# 配置默认网关
New-NetRoute -InterfaceIndex $adapter.ifIndex -NextHop $defaultGateway -DestinationPrefix "0.0.0.0/0"

网络流量监控:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 创建网络流量监控函数
function Monitor-NetworkTraffic {
param(
[string]$InterfaceName,
[int]$Duration = 60
)

$endTime = (Get-Date).AddSeconds($Duration)
$adapter = Get-NetAdapter -Name $InterfaceName

Write-Host "开始监控 $InterfaceName 的网络流量..."
Write-Host "监控时长:$Duration 秒"

while ((Get-Date) -lt $endTime) {
$stats = Get-NetAdapterStatistics -Name $InterfaceName
Write-Host "`n当前时间:$(Get-Date -Format 'HH:mm:ss')"
Write-Host "接收字节:$($stats.ReceivedBytes)"
Write-Host "发送字节:$($stats.SentBytes)"
Start-Sleep -Seconds 1
}
}

一些实用的网络操作技巧:

  1. DNS 解析:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # DNS 解析和反向解析
    $hostname = "www.baidu.com"
    $ip = "8.8.8.8"

    # 正向解析
    $dnsResult = Resolve-DnsName -Name $hostname
    Write-Host "`n$hostname 的IP地址:"
    $dnsResult | ForEach-Object { $_.IPAddress }

    # 反向解析
    $reverseResult = Resolve-DnsName -Name $ip -Type PTR
    Write-Host "`n$ip 的主机名:"
    $reverseResult.NameHost
  2. 端口扫描:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 简单的端口扫描函数
    function Test-Port {
    param(
    [string]$ComputerName,
    [int[]]$Ports = @(80,443,3389,22)
    )

    foreach ($port in $Ports) {
    $result = Test-NetConnection -ComputerName $ComputerName -Port $port -WarningAction SilentlyContinue
    Write-Host "端口 $port$($result.TcpTestSucceeded)"
    }
    }
  3. 网络共享管理:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 创建网络共享
    $shareName = "DataShare"
    $path = "C:\SharedData"
    $description = "数据共享文件夹"

    # 创建文件夹
    New-Item -ItemType Directory -Path $path -Force

    # 创建共享
    New-SmbShare -Name $shareName -Path $path -Description $description -FullAccess "Everyone"

    # 设置共享权限
    Grant-SmbShareAccess -Name $shareName -AccountName "Domain\Users" -AccessRight Read

这些技巧将帮助您更有效地处理网络操作。记住,在进行网络配置时,始终要注意网络安全性和性能影响。同时,建议在测试环境中先验证网络配置的正确性。

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
function Get-SecurityAudit {
[CmdletBinding()]
param(
[ValidateSet('Basic','Advanced')]
[string]$AuditLevel = 'Basic'
)

$report = [PSCustomObject]@{
FailedLogins = @()
OpenPorts = @()
WeakPermissions = @()
ComplianceScore = 0
}

try {
# 分析安全事件日志
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4625
StartTime = (Get-Date).AddDays(-7)
} -MaxEvents 1000
$report.FailedLogins = $events | Select-Object -ExpandProperty Message

# 扫描开放端口
$report.OpenPorts = Get-NetTCPConnection |
Where-Object State -eq 'Listen' |
Select-Object LocalAddress,LocalPort

# 高级权限检查
if($AuditLevel -eq 'Advanced') {
$report.WeakPermissions = Get-ChildItem -Path $env:ProgramFiles -Recurse |
Where-Object { $_.PSAccessControl.Access.IdentityReference -contains 'Everyone' }
}

# 计算合规分数
$totalChecks = 3
$passed = ([bool]!$report.FailedLogins.Count) +
([bool]!$report.OpenPorts.Count) +
([bool]!$report.WeakPermissions.Count)
$report.ComplianceScore = [math]::Round(($passed / $totalChecks) * 100)
}
catch {
Write-Warning "安全审计异常: $_"
}

return $report
}

实现原理:

  1. 通过Get-WinEvent查询安全事件日志,检测暴力破解行为
  2. 使用Get-NetTCPConnection发现异常监听端口
  3. 高级模式扫描程序目录权限配置
  4. 基于检测结果计算系统合规分数

使用示例:

1
2
3
4
5
# 基本审计
Get-SecurityAudit

# 高级审计
Get-SecurityAudit -AuditLevel Advanced

最佳实践:

  1. 与SIEM系统集成实现集中告警
  2. 设置基线配置进行差异对比
  3. 定期生成PDF格式审计报告
  4. 实现自动修复高风险项功能

注意事项:
• 需要本地管理员权限执行
• 端口扫描可能触发安全告警
• 建议在维护窗口执行深度扫描

PowerShell 技能连载 - Serverless 管理

在无服务器计算时代,PowerShell可以帮助我们更好地管理Serverless应用。本文将介绍如何使用PowerShell构建一个Serverless管理系统,包括函数管理、触发器配置和监控分析等功能。

函数管理

首先,让我们创建一个用于管理Serverless函数的函数:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function Manage-ServerlessFunctions {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$FunctionID,

[Parameter()]
[string[]]$FunctionTypes,

[Parameter()]
[ValidateSet("Create", "Update", "Delete")]
[string]$OperationMode = "Create",

[Parameter()]
[hashtable]$FunctionConfig,

[Parameter()]
[string]$LogPath
)

try {
$manager = [PSCustomObject]@{
FunctionID = $FunctionID
StartTime = Get-Date
FunctionStatus = @{}
Operations = @{}
Issues = @()
}

# 获取函数配置
$config = Get-FunctionConfig -FunctionID $FunctionID

# 管理函数
foreach ($type in $FunctionTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Operations = @{}
Issues = @()
}

# 应用函数配置
$typeConfig = Apply-FunctionConfig `
-Config $config `
-Type $type `
-Mode $OperationMode `
-Settings $FunctionConfig

$status.Config = $typeConfig

# 执行函数操作
$operations = Execute-FunctionOperations `
-Type $type `
-Config $typeConfig

$status.Operations = $operations
$manager.Operations[$type] = $operations

# 检查函数问题
$issues = Check-FunctionIssues `
-Operations $operations `
-Config $typeConfig

$status.Issues = $issues
$manager.Issues += $issues

# 更新函数状态
if ($issues.Count -gt 0) {
$status.Status = "Warning"
}
else {
$status.Status = "Success"
}

$manager.FunctionStatus[$type] = $status
}

# 记录函数日志
if ($LogPath) {
$manager | ConvertTo-Json -Depth 10 | Out-File -FilePath $LogPath
}

# 更新管理器状态
$manager.EndTime = Get-Date

return $manager
}
catch {
Write-Error "Serverless函数管理失败:$_"
return $null
}
}

触发器配置

接下来,创建一个用于管理触发器配置的函数:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function Configure-ServerlessTriggers {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TriggerID,

[Parameter()]
[string[]]$TriggerTypes,

[Parameter()]
[ValidateSet("HTTP", "Timer", "Queue", "Blob")]
[string]$TriggerMode = "HTTP",

[Parameter()]
[hashtable]$TriggerConfig,

[Parameter()]
[string]$ReportPath
)

try {
$configurator = [PSCustomObject]@{
TriggerID = $TriggerID
StartTime = Get-Date
TriggerStatus = @{}
Configurations = @{}
Issues = @()
}

# 获取触发器配置
$config = Get-TriggerConfig -TriggerID $TriggerID

# 管理触发器
foreach ($type in $TriggerTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Configurations = @{}
Issues = @()
}

# 应用触发器配置
$typeConfig = Apply-TriggerConfig `
-Config $config `
-Type $type `
-Mode $TriggerMode `
-Settings $TriggerConfig

$status.Config = $typeConfig

# 配置触发器
$configurations = Configure-TriggerResources `
-Type $type `
-Config $typeConfig

$status.Configurations = $configurations
$configurator.Configurations[$type] = $configurations

# 检查触发器问题
$issues = Check-TriggerIssues `
-Configurations $configurations `
-Config $typeConfig

$status.Issues = $issues
$configurator.Issues += $issues

# 更新触发器状态
if ($issues.Count -gt 0) {
$status.Status = "Warning"
}
else {
$status.Status = "Success"
}

$configurator.TriggerStatus[$type] = $status
}

# 生成报告
if ($ReportPath) {
$report = Generate-TriggerReport `
-Configurator $configurator `
-Config $config

$report | ConvertTo-Json -Depth 10 | Out-File -FilePath $ReportPath
}

# 更新配置器状态
$configurator.EndTime = Get-Date

return $configurator
}
catch {
Write-Error "Serverless触发器配置失败:$_"
return $null
}
}

监控分析

最后,创建一个用于管理监控分析的函数:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function Monitor-ServerlessPerformance {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$MonitorID,

[Parameter()]
[string[]]$MonitorTypes,

[Parameter()]
[ValidateSet("Metrics", "Logs", "Events")]
[string]$MonitorMode = "Metrics",

[Parameter()]
[hashtable]$MonitorConfig,

[Parameter()]
[string]$ReportPath
)

try {
$monitor = [PSCustomObject]@{
MonitorID = $MonitorID
StartTime = Get-Date
MonitorStatus = @{}
Metrics = @{}
Alerts = @()
}

# 获取监控配置
$config = Get-MonitorConfig -MonitorID $MonitorID

# 管理监控
foreach ($type in $MonitorTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Metrics = @{}
Alerts = @()
}

# 应用监控配置
$typeConfig = Apply-MonitorConfig `
-Config $config `
-Type $type `
-Mode $MonitorMode `
-Settings $MonitorConfig

$status.Config = $typeConfig

# 收集监控指标
$metrics = Collect-ServerlessMetrics `
-Type $type `
-Config $typeConfig

$status.Metrics = $metrics
$monitor.Metrics[$type] = $metrics

# 检查监控告警
$alerts = Check-MonitorAlerts `
-Metrics $metrics `
-Config $typeConfig

$status.Alerts = $alerts
$monitor.Alerts += $alerts

# 更新监控状态
if ($alerts.Count -gt 0) {
$status.Status = "Warning"
}
else {
$status.Status = "Normal"
}

$monitor.MonitorStatus[$type] = $status
}

# 生成报告
if ($ReportPath) {
$report = Generate-MonitorReport `
-Monitor $monitor `
-Config $config

$report | ConvertTo-Json -Depth 10 | Out-File -FilePath $ReportPath
}

# 更新监控器状态
$monitor.EndTime = Get-Date

return $monitor
}
catch {
Write-Error "Serverless监控分析失败:$_"
return $null
}
}

使用示例

以下是如何使用这些函数来管理Serverless环境的示例:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 管理Serverless函数
$manager = Manage-ServerlessFunctions -FunctionID "FUNCTION001" `
-FunctionTypes @("HTTP", "Timer", "Queue") `
-OperationMode "Create" `
-FunctionConfig @{
"HTTP" = @{
"Name" = "http-function"
"Runtime" = "PowerShell"
"Version" = "7.2"
"Memory" = 256
"Timeout" = 30
"Bindings" = @{
"Type" = "httpTrigger"
"Direction" = "in"
"Name" = "req"
"Methods" = @("GET", "POST")
"AuthLevel" = "function"
}
}
"Timer" = @{
"Name" = "timer-function"
"Runtime" = "PowerShell"
"Version" = "7.2"
"Memory" = 256
"Timeout" = 30
"Bindings" = @{
"Type" = "timerTrigger"
"Direction" = "in"
"Name" = "timer"
"Schedule" = "0 */5 * * * *"
}
}
"Queue" = @{
"Name" = "queue-function"
"Runtime" = "PowerShell"
"Version" = "7.2"
"Memory" = 256
"Timeout" = 30
"Bindings" = @{
"Type" = "queueTrigger"
"Direction" = "in"
"Name" = "queue"
"QueueName" = "myqueue"
"Connection" = "AzureWebJobsStorage"
}
}
} `
-LogPath "C:\Logs\function_management.json"

# 配置函数触发器
$configurator = Configure-ServerlessTriggers -TriggerID "TRIGGER001" `
-TriggerTypes @("HTTP", "Timer", "Queue") `
-TriggerMode "HTTP" `
-TriggerConfig @{
"HTTP" = @{
"Route" = "api/process"
"Methods" = @("GET", "POST")
"AuthLevel" = "function"
"Cors" = @{
"Origins" = @("https://example.com")
"Methods" = @("GET", "POST")
"Headers" = @("Content-Type", "Authorization")
}
}
"Timer" = @{
"Schedule" = "0 */5 * * * *"
"UseMonitor" = $true
"RunOnStartup" = $true
}
"Queue" = @{
"QueueName" = "myqueue"
"Connection" = "AzureWebJobsStorage"
"BatchSize" = 16
"MaxDequeueCount" = 5
}
} `
-ReportPath "C:\Reports\trigger_configuration.json"

# 监控函数性能
$monitor = Monitor-ServerlessPerformance -MonitorID "MONITOR001" `
-MonitorTypes @("Execution", "Memory", "Network") `
-MonitorMode "Metrics" `
-MonitorConfig @{
"Execution" = @{
"Metrics" = @("Duration", "Executions", "SuccessRate")
"Threshold" = 80
"Interval" = 60
"Alert" = $true
}
"Memory" = @{
"Metrics" = @("MemoryUsage", "MemoryLimit")
"Threshold" = 90
"Interval" = 60
"Alert" = $true
}
"Network" = @{
"Metrics" = @("Requests", "Latency", "Errors")
"Threshold" = 85
"Interval" = 60
"Alert" = $true
}
} `
-ReportPath "C:\Reports\function_monitoring.json"

最佳实践

  1. 实施函数管理
  2. 配置触发器服务
  3. 监控性能指标
  4. 保持详细的部署记录
  5. 定期进行健康检查
  6. 实施监控策略
  7. 建立告警机制
  8. 保持系统文档更新

PowerShell 技能连载 - 集合操作方法

基础集合操作

1
2
3
4
5
6
7
8
9
10
11
# 创建强类型集合
[System.Collections.Generic.List[string]]$list = @()
$list.AddRange(@('Server01','Server02'))

# 哈希表快速查询
$configTable = @{
Timeout = 30
Retries = 3
LogPath = 'C:\Logs'
}
$configTable.ContainsKey('Timeout')

应用场景

  1. 数据过滤

    1
    Get-Process | Where-Object {$_.CPU -gt 100 -and $_.Name -notmatch '^svchost$'}
  2. 批量重命名

    1
    2
    3
    4
    5
    $files = Get-ChildItem *.log
    $files | ForEach-Object {
    $newName = $_.Name -replace '_old','_new'
    Rename-Item $_ $newName
    }

最佳实践

  1. 使用泛型集合提升性能

    1
    2
    $queue = [System.Collections.Queue]::new()
    1..10000 | ForEach-Object {$queue.Enqueue($_)}
  2. 利用管道优化内存使用

    1
    2
    # 流式处理大文件
    Get-Content huge.log | Where-Object {$_ -match 'ERROR'} | Export-Csv errors.csv
  3. 嵌套集合处理

    1
    2
    3
    4
    5
    6
    $serverData = @(
    [PSCustomObject]@{Name='WEB01'; Role='Frontend'}
    [PSCustomObject]@{Name='DB01'; Role='Database'}
    )

    $serverData.Where({$_.Role -eq 'Frontend'}).ForEach({$_.Name})

PowerShell 技能连载 - Exchange 管理技巧

在 PowerShell 中管理 Exchange 是一项重要任务,本文将介绍一些实用的 Exchange 管理技巧。

首先,让我们看看基本的 Exchange 操作:

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
# 创建 Exchange 邮箱管理函数
function Manage-ExchangeMailbox {
param(
[string]$UserPrincipalName,
[string]$DisplayName,
[string]$Alias,
[string]$Database,
[ValidateSet('Create', 'Update', 'Delete', 'Disable', 'Enable')]
[string]$Action
)

try {
Import-Module ExchangeOnlineManagement

switch ($Action) {
'Create' {
New-Mailbox -UserPrincipalName $UserPrincipalName -DisplayName $DisplayName -Alias $Alias -Database $Database
Write-Host "邮箱 $UserPrincipalName 创建成功"
}
'Update' {
Set-Mailbox -Identity $UserPrincipalName -DisplayName $DisplayName -Alias $Alias
Write-Host "邮箱 $UserPrincipalName 更新成功"
}
'Delete' {
Remove-Mailbox -Identity $UserPrincipalName -Confirm:$false
Write-Host "邮箱 $UserPrincipalName 删除成功"
}
'Disable' {
Disable-Mailbox -Identity $UserPrincipalName -Confirm:$false
Write-Host "邮箱 $UserPrincipalName 已禁用"
}
'Enable' {
Enable-Mailbox -Identity $UserPrincipalName
Write-Host "邮箱 $UserPrincipalName 已启用"
}
}
}
catch {
Write-Host "Exchange 操作失败:$_"
}
}

Exchange 分发组管理:

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
# 创建 Exchange 分发组管理函数
function Manage-ExchangeDistributionGroup {
param(
[string]$Name,
[string]$DisplayName,
[string[]]$Members,
[ValidateSet('Create', 'Update', 'Delete', 'AddMembers', 'RemoveMembers')]
[string]$Action
)

try {
Import-Module ExchangeOnlineManagement

switch ($Action) {
'Create' {
New-DistributionGroup -Name $Name -DisplayName $DisplayName
Write-Host "分发组 $Name 创建成功"
}
'Update' {
Set-DistributionGroup -Identity $Name -DisplayName $DisplayName
Write-Host "分发组 $Name 更新成功"
}
'Delete' {
Remove-DistributionGroup -Identity $Name -Confirm:$false
Write-Host "分发组 $Name 删除成功"
}
'AddMembers' {
Add-DistributionGroupMember -Identity $Name -Member $Members
Write-Host "成员已添加到分发组 $Name"
}
'RemoveMembers' {
Remove-DistributionGroupMember -Identity $Name -Member $Members -Confirm:$false
Write-Host "成员已从分发组 $Name 移除"
}
}
}
catch {
Write-Host "Exchange 分发组操作失败:$_"
}
}

Exchange 邮件规则管理:

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
# 创建 Exchange 邮件规则管理函数
function Manage-ExchangeTransportRule {
param(
[string]$Name,
[string]$Description,
[string[]]$Conditions,
[string[]]$Actions,
[ValidateSet('Create', 'Update', 'Delete', 'Enable', 'Disable')]
[string]$Action
)

try {
Import-Module ExchangeOnlineManagement

switch ($Action) {
'Create' {
New-TransportRule -Name $Name -Description $Description -Conditions $Conditions -Actions $Actions
Write-Host "传输规则 $Name 创建成功"
}
'Update' {
Set-TransportRule -Identity $Name -Description $Description -Conditions $Conditions -Actions $Actions
Write-Host "传输规则 $Name 更新成功"
}
'Delete' {
Remove-TransportRule -Identity $Name -Confirm:$false
Write-Host "传输规则 $Name 删除成功"
}
'Enable' {
Enable-TransportRule -Identity $Name
Write-Host "传输规则 $Name 已启用"
}
'Disable' {
Disable-TransportRule -Identity $Name
Write-Host "传输规则 $Name 已禁用"
}
}
}
catch {
Write-Host "Exchange 传输规则操作失败:$_"
}
}

Exchange 邮箱权限管理:

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
# 创建 Exchange 邮箱权限管理函数
function Manage-ExchangeMailboxPermission {
param(
[string]$Mailbox,
[string]$User,
[string[]]$AccessRights,
[ValidateSet('Grant', 'Revoke', 'Reset')]
[string]$Action
)

try {
Import-Module ExchangeOnlineManagement

switch ($Action) {
'Grant' {
Add-MailboxPermission -Identity $Mailbox -User $User -AccessRights $AccessRights
Write-Host "权限已授予 $User 访问 $Mailbox"
}
'Revoke' {
Remove-MailboxPermission -Identity $Mailbox -User $User -AccessRights $AccessRights -Confirm:$false
Write-Host "权限已从 $User 撤销访问 $Mailbox"
}
'Reset' {
Get-MailboxPermission -Identity $Mailbox | Where-Object { $_.User -ne "NT AUTHORITY\SELF" } | ForEach-Object {
Remove-MailboxPermission -Identity $Mailbox -User $_.User -AccessRights $_.AccessRights -Confirm:$false
}
Write-Host "邮箱 $Mailbox 的权限已重置"
}
}
}
catch {
Write-Host "Exchange 邮箱权限操作失败:$_"
}
}

Exchange 审计和报告:

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
# 创建 Exchange 审计和报告函数
function Get-ExchangeAuditReport {
param(
[datetime]$StartDate,
[datetime]$EndDate,
[string]$ReportPath
)

try {
Import-Module ExchangeOnlineManagement

$report = @()

# 获取邮箱访问日志
$mailboxAccess = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -RecordType MailboxAccessed
$mailboxAccess | ForEach-Object {
[PSCustomObject]@{
Type = "Mailbox Access"
User = $_.UserIds
Mailbox = $_.MailboxOwnerUPN
Time = $_.CreationDate
IP = $_.ClientIP
}
}

# 获取邮件发送日志
$mailSent = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -RecordType Send
$mailSent | ForEach-Object {
[PSCustomObject]@{
Type = "Mail Sent"
User = $_.UserIds
Recipients = $_.Recipients
Time = $_.CreationDate
Subject = $_.Subject
}
}

$report = $mailboxAccess + $mailSent
$report | Export-Csv -Path $ReportPath -NoTypeInformation

return [PSCustomObject]@{
TotalEvents = $report.Count
MailboxAccess = $mailboxAccess.Count
MailSent = $mailSent.Count
ReportPath = $ReportPath
}
}
catch {
Write-Host "Exchange 审计报告生成失败:$_"
}
}

这些技巧将帮助您更有效地管理 Exchange。记住,在处理 Exchange 时,始终要注意安全性和性能。同时,建议使用适当的错误处理和日志记录机制来跟踪所有操作。

PowerShell 技能连载 - 事件日志管理技巧

在 PowerShell 中管理事件日志是系统管理和故障排查的重要任务。本文将介绍一些实用的事件日志管理技巧。

首先,让我们看看事件日志的基本操作:

1
2
3
4
5
# 获取系统事件日志
$logs = Get-EventLog -List | Where-Object { $_.LogDisplayName -match "System|Application|Security" }

Write-Host "`n系统事件日志列表:"
$logs | Format-Table LogDisplayName, Entries, MaximumKilobytes, OverflowAction -AutoSize

事件日志查询:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 创建事件日志查询函数
function Get-SystemEvents {
param(
[string]$LogName = "System",
[int]$Hours = 24,
[string[]]$EventTypes = @("Error", "Warning")
)

$startTime = (Get-Date).AddHours(-$Hours)

$events = Get-EventLog -LogName $LogName -After $startTime |
Where-Object { $_.EntryType -in $EventTypes } |
Select-Object TimeGenerated, EntryType, Source, EventID, Message

Write-Host "`n最近 $Hours 小时内的 $LogName 日志:"
$events | Format-Table TimeGenerated, EntryType, Source, EventID -AutoSize

# 统计事件类型
$events | Group-Object EntryType | ForEach-Object {
Write-Host "`n$($_.Name) 事件数量:$($_.Count)"
}
}

事件日志清理:

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
# 创建事件日志清理函数
function Clear-EventLogs {
param(
[string[]]$LogNames = @("System", "Application", "Security"),
[int]$DaysToKeep = 30
)

$cutoffDate = (Get-Date).AddDays(-$DaysToKeep)

foreach ($logName in $LogNames) {
try {
$log = Get-EventLog -LogName $logName
$oldEvents = $log.Entries | Where-Object { $_.TimeGenerated -lt $cutoffDate }

if ($oldEvents) {
Write-Host "`n清理 $logName 日志..."
Write-Host "将删除 $($oldEvents.Count) 条旧记录"

# 导出旧事件到文件
$exportPath = "C:\LogBackup\$logName_$(Get-Date -Format 'yyyyMMdd').evt"
$oldEvents | Export-Clixml -Path $exportPath

# 清理日志
Clear-EventLog -LogName $logName
Write-Host "日志已清理"
}
else {
Write-Host "`n$logName 日志中没有需要清理的记录"
}
}
catch {
Write-Host "清理 $logName 日志时出错:$_"
}
}
}

事件日志监控:

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
# 创建事件日志监控函数
function Watch-EventLog {
param(
[string]$LogName = "System",
[string[]]$EventTypes = @("Error", "Warning"),
[int]$Duration = 300
)

$endTime = (Get-Date).AddSeconds($Duration)
Write-Host "开始监控 $LogName 日志"
Write-Host "监控时长:$Duration 秒"

while ((Get-Date) -lt $endTime) {
$events = Get-EventLog -LogName $LogName -Newest 100 |
Where-Object { $_.EntryType -in $EventTypes }

if ($events) {
Write-Host "`n检测到新事件:"
$events | ForEach-Object {
Write-Host "`n时间:$($_.TimeGenerated)"
Write-Host "类型:$($_.EntryType)"
Write-Host "来源:$($_.Source)"
Write-Host "事件ID:$($_.EventID)"
Write-Host "消息:$($_.Message)"
}
}

Start-Sleep -Seconds 5
}
}

一些实用的事件日志管理技巧:

  1. 事件日志分析:

    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
    # 分析事件日志模式
    function Analyze-EventPatterns {
    param(
    [string]$LogName = "System",
    [int]$Hours = 24
    )

    $startTime = (Get-Date).AddHours(-$Hours)
    $events = Get-EventLog -LogName $LogName -After $startTime

    Write-Host "`n事件来源统计:"
    $events | Group-Object Source |
    Sort-Object Count -Descending |
    Select-Object -First 10 |
    Format-Table Name, Count -AutoSize

    Write-Host "`n事件类型分布:"
    $events | Group-Object EntryType |
    Format-Table Name, Count -AutoSize

    Write-Host "`n最常见的事件ID:"
    $events | Group-Object EventID |
    Sort-Object Count -Descending |
    Select-Object -First 10 |
    Format-Table Name, Count -AutoSize
    }
  2. 事件日志导出:

    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
    # 导出事件日志
    function Export-EventLogs {
    param(
    [string]$LogName,
    [DateTime]$StartTime,
    [DateTime]$EndTime,
    [string]$ExportPath
    )

    # 创建导出目录
    New-Item -ItemType Directory -Path $ExportPath -Force

    # 导出事件日志
    $events = Get-EventLog -LogName $LogName -After $StartTime -Before $EndTime

    # 导出为CSV
    $csvPath = Join-Path $ExportPath "$LogName_$(Get-Date -Format 'yyyyMMdd').csv"
    $events | Export-Csv -Path $csvPath -NoTypeInformation

    # 导出为XML
    $xmlPath = Join-Path $ExportPath "$LogName_$(Get-Date -Format 'yyyyMMdd').xml"
    $events | Export-Clixml -Path $xmlPath

    Write-Host "`n已导出事件日志:"
    Write-Host "CSV文件:$csvPath"
    Write-Host "XML文件:$xmlPath"
    Write-Host "事件数量:$($events.Count)"
    }
  3. 事件日志过滤:

    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
    # 创建高级事件日志过滤函数
    function Get-FilteredEvents {
    param(
    [string]$LogName,
    [string[]]$EventTypes,
    [string[]]$Sources,
    [int[]]$EventIDs,
    [int]$Hours = 24
    )

    $startTime = (Get-Date).AddHours(-$Hours)

    $events = Get-EventLog -LogName $LogName -After $startTime |
    Where-Object {
    $_.EntryType -in $EventTypes -and
    $_.Source -in $Sources -and
    $_.EventID -in $EventIDs
    }

    Write-Host "`n过滤结果:"
    $events | Format-Table TimeGenerated, EntryType, Source, EventID, Message -AutoSize

    # 生成统计报告
    Write-Host "`n统计信息:"
    Write-Host "总事件数:$($events.Count)"
    Write-Host "`n按事件类型统计:"
    $events | Group-Object EntryType | Format-Table Name, Count -AutoSize
    Write-Host "`n按来源统计:"
    $events | Group-Object Source | Format-Table Name, Count -AutoSize
    }

这些技巧将帮助您更有效地管理事件日志。记住,在处理事件日志时,始终要注意日志的安全性和完整性。同时,建议定期备份重要的事件日志,以便进行历史分析和故障排查。

PowerShell 技能连载 - 系统优化技巧

在 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
# 创建系统性能分析函数
function Get-SystemPerformance {
param(
[int]$Duration = 3600,
[int]$Interval = 60
)

try {
$metrics = @()
$endTime = Get-Date
$startTime = $endTime.AddSeconds(-$Duration)

while ($startTime -lt $endTime) {
$cpu = Get-Counter '\Processor(_Total)\% Processor Time'
$memory = Get-Counter '\Memory\Available MBytes'
$disk = Get-Counter '\PhysicalDisk(_Total)\% Disk Time'

$metrics += [PSCustomObject]@{
Time = Get-Date
CPUUsage = $cpu.CounterSamples.CookedValue
AvailableMemory = $memory.CounterSamples.CookedValue
DiskUsage = $disk.CounterSamples.CookedValue
}

$startTime = $startTime.AddSeconds($Interval)
Start-Sleep -Seconds $Interval
}

return [PSCustomObject]@{
Duration = $Duration
Interval = $Interval
Metrics = $metrics
}
}
catch {
Write-Host "系统性能分析失败:$_"
}
}

系统服务优化:

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
# 创建系统服务优化函数
function Optimize-SystemServices {
param(
[string[]]$Services,
[ValidateSet('Startup', 'Manual', 'Disabled')]
[string]$StartupType
)

try {
foreach ($service in $Services) {
$svc = Get-Service -Name $service
if ($svc) {
Set-Service -Name $service -StartupType $StartupType
Write-Host "服务 $service 已设置为 $StartupType"
}
}

return [PSCustomObject]@{
Services = $Services
StartupType = $StartupType
Status = "完成"
}
}
catch {
Write-Host "系统服务优化失败:$_"
}
}

系统注册表优化:

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
# 创建系统注册表优化函数
function Optimize-SystemRegistry {
param(
[string]$RegistryPath,
[hashtable]$Settings
)

try {
if (-not (Test-Path $RegistryPath)) {
New-Item -Path $RegistryPath -Force
}

foreach ($key in $Settings.Keys) {
$value = $Settings[$key]
Set-ItemProperty -Path $RegistryPath -Name $key -Value $value
Write-Host "注册表项 $key 已设置为 $value"
}

return [PSCustomObject]@{
RegistryPath = $RegistryPath
Settings = $Settings
Status = "完成"
}
}
catch {
Write-Host "系统注册表优化失败:$_"
}
}

系统磁盘优化:

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
# 创建系统磁盘优化函数
function Optimize-SystemDisk {
param(
[string]$DriveLetter,
[switch]$Defrag,
[switch]$Cleanup
)

try {
$results = @()

if ($Defrag) {
$defragResult = Optimize-Volume -DriveLetter $DriveLetter -Defrag -Verbose
$results += [PSCustomObject]@{
Operation = "Defrag"
Status = $defragResult.Status
SpaceSaved = $defragResult.SpaceSaved
}
}

if ($Cleanup) {
$cleanupResult = Clear-RecycleBin -DriveLetter $DriveLetter -Force
$results += [PSCustomObject]@{
Operation = "Cleanup"
Status = "完成"
ItemsRemoved = $cleanupResult.Count
}
}

return [PSCustomObject]@{
DriveLetter = $DriveLetter
Operations = $results
}
}
catch {
Write-Host "系统磁盘优化失败:$_"
}
}

系统网络优化:

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
# 创建系统网络优化函数
function Optimize-SystemNetwork {
param(
[string]$AdapterName,
[hashtable]$Settings
)

try {
$adapter = Get-NetAdapter -Name $AdapterName
if ($adapter) {
foreach ($key in $Settings.Keys) {
$value = $Settings[$key]
Set-NetAdapterAdvancedProperty -Name $AdapterName -RegistryKeyword $key -RegistryValue $value
Write-Host "网络适配器 $AdapterName$key 已设置为 $value"
}

return [PSCustomObject]@{
AdapterName = $AdapterName
Settings = $Settings
Status = "完成"
}
}
else {
Write-Host "未找到网络适配器:$AdapterName"
}
}
catch {
Write-Host "系统网络优化失败:$_"
}
}

这些技巧将帮助您更有效地优化系统性能。记住,在优化系统时,始终要注意安全性和稳定性。同时,建议使用适当的错误处理和日志记录机制来跟踪所有操作。

PowerShell 技能连载 - 基础设施即代码实践

在现代IT运维领域,基础设施即代码(Infrastructure as Code, IaC)已成为标准实践。本文将介绍如何使用PowerShell实现高效的IaC解决方案。

首先,让我们创建一个基础环境配置定义函数:

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
59
60
61
62
# 创建环境配置定义函数
function New-InfrastructureDefinition {
param(
[Parameter(Mandatory)]
[string]$EnvironmentName,

[Parameter(Mandatory)]
[string]$OutputPath,

[string]$Description = "",

[ValidateSet("Development", "Testing", "Staging", "Production")]
[string]$EnvironmentType = "Development",

[switch]$Force
)

try {
# 创建基础环境配置对象
$infrastructureDefinition = [PSCustomObject]@{
EnvironmentName = $EnvironmentName
EnvironmentType = $EnvironmentType
Description = $Description
CreatedBy = $env:USERNAME
CreatedOn = Get-Date
Version = "1.0"
Resources = @{
VirtualMachines = @()
NetworkResources = @()
StorageResources = @()
SecurityResources = @()
DatabaseResources = @()
ApplicationResources = @()
}
Dependencies = @{}
DeploymentOrder = @()
State = "Draft"
Metadata = @{}
}

# 创建JSON定义文件
$definitionFile = Join-Path -Path $OutputPath -ChildPath "$EnvironmentName.json"

if ((Test-Path -Path $definitionFile) -and (-not $Force)) {
throw "定义文件 '$definitionFile' 已存在。使用 -Force 参数覆盖现有文件。"
}

# 创建输出目录(如果不存在)
if (-not (Test-Path -Path $OutputPath)) {
New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
}

# 保存定义
$infrastructureDefinition | ConvertTo-Json -Depth 10 | Out-File -FilePath $definitionFile -Encoding UTF8

Write-Host "已创建基础设施定义: $definitionFile" -ForegroundColor Green
return $infrastructureDefinition
}
catch {
Write-Error "创建基础设施定义时出错: $_"
}
}

接下来,添加虚拟机资源定义:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 添加虚拟机资源定义
function Add-VMResource {
param(
[Parameter(Mandatory, ValueFromPipeline)]
[PSObject]$InfrastructureDefinition,

[Parameter(Mandatory)]
[string]$VMName,

[Parameter(Mandatory)]
[string]$Size,

[string]$OSType = "Windows",

[string]$OSVersion = "2022-Datacenter",

[string]$NetworkName,

[string]$SubnetName,

[hashtable]$Tags = @{},

[string[]]$DependsOn = @(),

[hashtable]$Properties = @{},

[string]$OutputPath
)

process {
try {
# 创建VM定义
$vmResource = [PSCustomObject]@{
Name = $VMName
ResourceType = "VirtualMachine"
Size = $Size
OSType = $OSType
OSVersion = $OSVersion
NetworkName = $NetworkName
SubnetName = $SubnetName
Tags = $Tags
Properties = $Properties
DependsOn = $DependsOn
ResourceId = [guid]::NewGuid().ToString()
CreatedOn = Get-Date
}

# 添加到定义中
$InfrastructureDefinition.Resources.VirtualMachines += $vmResource

# 添加依赖关系
foreach ($dependency in $DependsOn) {
if (-not $InfrastructureDefinition.Dependencies.ContainsKey($VMName)) {
$InfrastructureDefinition.Dependencies[$VMName] = @()
}
$InfrastructureDefinition.Dependencies[$VMName] += $dependency
}

# 如果提供了输出路径,更新定义文件
if ($OutputPath) {
$definitionFile = Join-Path -Path $OutputPath -ChildPath "$($InfrastructureDefinition.EnvironmentName).json"
$InfrastructureDefinition | ConvertTo-Json -Depth 10 | Out-File -FilePath $definitionFile -Encoding UTF8
Write-Host "已更新基础设施定义: $definitionFile" -ForegroundColor Green
}

return $InfrastructureDefinition
}
catch {
Write-Error "添加虚拟机资源定义时出错: $_"
}
}
}

添加网络资源定义:

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
59
60
61
62
63
64
65
66
67
# 添加网络资源定义
function Add-NetworkResource {
param(
[Parameter(Mandatory, ValueFromPipeline)]
[PSObject]$InfrastructureDefinition,

[Parameter(Mandatory)]
[string]$NetworkName,

[Parameter(Mandatory)]
[string]$AddressSpace,

[Parameter(Mandatory)]
[PSObject[]]$Subnets,

[bool]$EnableDnsSupport = $true,

[hashtable]$Tags = @{},

[string[]]$DependsOn = @(),

[hashtable]$Properties = @{},

[string]$OutputPath
)

process {
try {
# 创建网络定义
$networkResource = [PSCustomObject]@{
Name = $NetworkName
ResourceType = "VirtualNetwork"
AddressSpace = $AddressSpace
Subnets = $Subnets
EnableDnsSupport = $EnableDnsSupport
Tags = $Tags
Properties = $Properties
DependsOn = $DependsOn
ResourceId = [guid]::NewGuid().ToString()
CreatedOn = Get-Date
}

# 添加到定义中
$InfrastructureDefinition.Resources.NetworkResources += $networkResource

# 添加依赖关系
foreach ($dependency in $DependsOn) {
if (-not $InfrastructureDefinition.Dependencies.ContainsKey($NetworkName)) {
$InfrastructureDefinition.Dependencies[$NetworkName] = @()
}
$InfrastructureDefinition.Dependencies[$NetworkName] += $dependency
}

# 如果提供了输出路径,更新定义文件
if ($OutputPath) {
$definitionFile = Join-Path -Path $OutputPath -ChildPath "$($InfrastructureDefinition.EnvironmentName).json"
$InfrastructureDefinition | ConvertTo-Json -Depth 10 | Out-File -FilePath $definitionFile -Encoding UTF8
Write-Host "已更新基础设施定义: $definitionFile" -ForegroundColor Green
}

return $InfrastructureDefinition
}
catch {
Write-Error "添加网络资源定义时出错: $_"
}
}
}

生成部署顺序:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# 生成资源部署顺序
function Set-DeploymentOrder {
param(
[Parameter(Mandatory, ValueFromPipeline)]
[PSObject]$InfrastructureDefinition,

[switch]$Validate,

[string]$OutputPath
)

process {
try {
# 创建依赖图
$dependencyGraph = @{}
$resourceList = @()

# 收集所有资源
foreach ($vmResource in $InfrastructureDefinition.Resources.VirtualMachines) {
$resourceList += $vmResource.Name
$dependencyGraph[$vmResource.Name] = $vmResource.DependsOn
}

foreach ($netResource in $InfrastructureDefinition.Resources.NetworkResources) {
$resourceList += $netResource.Name
$dependencyGraph[$netResource.Name] = $netResource.DependsOn
}

# 添加其他资源类型...

# 检测循环依赖
$visited = @{}
$recStack = @{}

function Test-CyclicDependency {
param([string]$Node)

$visited[$Node] = $true
$recStack[$Node] = $true

foreach ($neighbor in $dependencyGraph[$Node]) {
if (-not $visited.ContainsKey($neighbor)) {
if (Test-CyclicDependency -Node $neighbor) {
return $true
}
}
elseif ($recStack.ContainsKey($neighbor)) {
return $true
}
}

$recStack.Remove($Node)
return $false
}

foreach ($resource in $resourceList) {
if (-not $visited.ContainsKey($resource)) {
if (Test-CyclicDependency -Node $resource) {
throw "检测到循环依赖关系。无法确定部署顺序。"
}
}
}

# 拓扑排序
$visited = @{}
$deploymentOrder = [System.Collections.ArrayList]::new()

function Sort-Topology {
param([string]$Node)

$visited[$Node] = $true

foreach ($neighbor in $dependencyGraph[$Node]) {
if (-not $visited.ContainsKey($neighbor)) {
Sort-Topology -Node $neighbor
}
}

$deploymentOrder.Add($Node) | Out-Null
}

foreach ($resource in $resourceList) {
if (-not $visited.ContainsKey($resource)) {
Sort-Topology -Node $resource
}
}

# 反转列表,因为我们需要先部署没有依赖的资源
[Array]::Reverse($deploymentOrder)

# 更新部署顺序
$InfrastructureDefinition.DeploymentOrder = $deploymentOrder

# 验证部署顺序
if ($Validate) {
Write-Host "验证部署顺序..." -ForegroundColor Yellow
$deploymentSet = @{}
$isValid = $true

foreach ($resource in $deploymentOrder) {
foreach ($dependency in $dependencyGraph[$resource]) {
if (-not $deploymentSet.ContainsKey($dependency)) {
Write-Host "错误: 资源 '$resource' 依赖于 '$dependency',但该资源尚未部署。" -ForegroundColor Red
$isValid = $false
}
}
$deploymentSet[$resource] = $true
}

if ($isValid) {
Write-Host "部署顺序有效。" -ForegroundColor Green
} else {
throw "部署顺序无效。请检查资源依赖关系。"
}
}

# 如果提供了输出路径,更新定义文件
if ($OutputPath) {
$definitionFile = Join-Path -Path $OutputPath -ChildPath "$($InfrastructureDefinition.EnvironmentName).json"
$InfrastructureDefinition | ConvertTo-Json -Depth 10 | Out-File -FilePath $definitionFile -Encoding UTF8
Write-Host "已更新基础设施定义: $definitionFile" -ForegroundColor Green
}

return $InfrastructureDefinition
}
catch {
Write-Error "生成部署顺序时出错: $_"
}
}
}

部署基础设施资源:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 部署基础设施资源
function Deploy-InfrastructureResource {
param(
[Parameter(Mandatory)]
[PSObject]$Resource,

[Parameter(Mandatory)]
[PSObject]$InfrastructureDefinition,

[switch]$WhatIf,

[PSObject]$DeploymentContext = @{}
)

try {
$resourceName = $Resource.Name
$resourceType = $Resource.ResourceType

Write-Host "开始部署资源: $resourceName (类型: $resourceType)" -ForegroundColor Cyan

switch ($resourceType) {
"VirtualMachine" {
if ($WhatIf) {
Write-Host "[WhatIf] 将创建虚拟机 '$resourceName' (大小: $($Resource.Size), OS: $($Resource.OSType)-$($Resource.OSVersion))" -ForegroundColor Yellow
} else {
# 这里是虚拟机部署的实际代码
# 示例: 使用 Azure PowerShell 模块创建虚拟机
Write-Host "正在创建虚拟机 '$resourceName'..." -ForegroundColor White

# 模拟部署
Start-Sleep -Seconds 2

# 返回部署结果
$deploymentResult = [PSCustomObject]@{
ResourceName = $resourceName
ResourceType = $resourceType
Status = "Success"
DeploymentId = [guid]::NewGuid().ToString()
DeploymentTime = Get-Date
Properties = @{
IPAddress = "10.0.0.$((Get-Random -Minimum 2 -Maximum 255))"
FQDN = "$resourceName.example.com"
}
}

Write-Host "虚拟机 '$resourceName' 部署成功" -ForegroundColor Green
return $deploymentResult
}
}
"VirtualNetwork" {
if ($WhatIf) {
Write-Host "[WhatIf] 将创建虚拟网络 '$resourceName' (地址空间: $($Resource.AddressSpace))" -ForegroundColor Yellow
} else {
# 这里是虚拟网络部署的实际代码
Write-Host "正在创建虚拟网络 '$resourceName'..." -ForegroundColor White

# 模拟部署
Start-Sleep -Seconds 1

# 返回部署结果
$deploymentResult = [PSCustomObject]@{
ResourceName = $resourceName
ResourceType = $resourceType
Status = "Success"
DeploymentId = [guid]::NewGuid().ToString()
DeploymentTime = Get-Date
Properties = @{
AddressSpace = $Resource.AddressSpace
SubnetCount = $Resource.Subnets.Count
}
}

Write-Host "虚拟网络 '$resourceName' 部署成功" -ForegroundColor Green
return $deploymentResult
}
}
default {
Write-Warning "不支持的资源类型: $resourceType"
}
}

if ($WhatIf) {
return [PSCustomObject]@{
ResourceName = $resourceName
ResourceType = $resourceType
Status = "WhatIf"
}
}
}
catch {
Write-Error "部署资源 '$resourceName' 时出错: $_"
return [PSCustomObject]@{
ResourceName = $resourceName
ResourceType = $resourceType
Status = "Failed"
Error = $_.ToString()
}
}
}

执行完整基础设施部署:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 部署完整基础设施
function Deploy-Infrastructure {
param(
[Parameter(Mandatory)]
[PSObject]$InfrastructureDefinition,

[switch]$WhatIf,

[switch]$Force,

[string]$DeploymentLogPath,

[scriptblock]$OnSuccessAction,

[scriptblock]$OnFailureAction
)

try {
$environmentName = $InfrastructureDefinition.EnvironmentName
$deploymentResults = @()
$deploymentContext = @{}
$deploymentStart = Get-Date
$deploymentSuccess = $true

Write-Host "开始部署环境: $environmentName" -ForegroundColor Cyan

# 检查是否有部署顺序
if ($InfrastructureDefinition.DeploymentOrder.Count -eq 0) {
Write-Warning "部署顺序为空。正在尝试生成部署顺序..."
$InfrastructureDefinition = Set-DeploymentOrder -InfrastructureDefinition $InfrastructureDefinition -Validate
}

# 创建资源映射
$resourceMap = @{}
foreach ($vmResource in $InfrastructureDefinition.Resources.VirtualMachines) {
$resourceMap[$vmResource.Name] = $vmResource
}

foreach ($netResource in $InfrastructureDefinition.Resources.NetworkResources) {
$resourceMap[$netResource.Name] = $netResource
}

# 按照部署顺序部署资源
foreach ($resourceName in $InfrastructureDefinition.DeploymentOrder) {
$resource = $resourceMap[$resourceName]

if (-not $resource) {
Write-Warning "资源 '$resourceName' 在部署顺序中但未找到资源定义。跳过。"
continue
}

$result = Deploy-InfrastructureResource -Resource $resource -InfrastructureDefinition $InfrastructureDefinition -WhatIf:$WhatIf -DeploymentContext $deploymentContext
$deploymentResults += $result

# 如果部署失败且未强制继续,则终止部署
if ($result.Status -eq "Failed" -and -not $Force) {
Write-Error "资源 '$resourceName' 部署失败。终止部署。"
$deploymentSuccess = $false
break
}

# 更新部署上下文
if ($result.Status -eq "Success") {
$deploymentContext[$resourceName] = $result
}
}

$deploymentEnd = Get-Date
$deploymentDuration = $deploymentEnd - $deploymentStart

# 生成部署摘要
$deploymentSummary = [PSCustomObject]@{
EnvironmentName = $environmentName
StartTime = $deploymentStart
EndTime = $deploymentEnd
Duration = $deploymentDuration
Status = if ($deploymentSuccess) { "Success" } else { "Failed" }
ResourceCount = $deploymentResults.Count
SuccessCount = ($deploymentResults | Where-Object { $_.Status -eq "Success" }).Count
FailedCount = ($deploymentResults | Where-Object { $_.Status -eq "Failed" }).Count
WhatIfCount = ($deploymentResults | Where-Object { $_.Status -eq "WhatIf" }).Count
DetailedResults = $deploymentResults
}

# 保存部署日志
if ($DeploymentLogPath) {
$logFile = Join-Path -Path $DeploymentLogPath -ChildPath "Deployment_$environmentName`_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"

# 创建目录(如果不存在)
if (-not (Test-Path -Path $DeploymentLogPath)) {
New-Item -Path $DeploymentLogPath -ItemType Directory -Force | Out-Null
}

$deploymentSummary | ConvertTo-Json -Depth 10 | Out-File -FilePath $logFile -Encoding UTF8
Write-Host "部署日志已保存至: $logFile" -ForegroundColor Green
}

# 部署成功或失败时执行的操作
if ($deploymentSuccess -and $OnSuccessAction) {
& $OnSuccessAction -DeploymentSummary $deploymentSummary
}
elseif (-not $deploymentSuccess -and $OnFailureAction) {
& $OnFailureAction -DeploymentSummary $deploymentSummary
}

# 输出部署摘要
Write-Host "部署摘要:" -ForegroundColor Cyan
Write-Host " 环境: $environmentName" -ForegroundColor White
Write-Host " 状态: $($deploymentSummary.Status)" -ForegroundColor $(if ($deploymentSummary.Status -eq "Success") { "Green" } else { "Red" })
Write-Host " 持续时间: $($deploymentDuration.TotalMinutes) 分钟" -ForegroundColor White
Write-Host " 资源总数: $($deploymentSummary.ResourceCount)" -ForegroundColor White
Write-Host " 成功: $($deploymentSummary.SuccessCount)" -ForegroundColor Green
Write-Host " 失败: $($deploymentSummary.FailedCount)" -ForegroundColor $(if ($deploymentSummary.FailedCount -gt 0) { "Red" } else { "White" })
Write-Host " WhatIf: $($deploymentSummary.WhatIfCount)" -ForegroundColor Yellow

return $deploymentSummary
}
catch {
Write-Error "部署环境 '$environmentName' 时出错: $_"
}
}

现在,让我们看一个使用示例:

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
# 定义输出路径
$outputPath = "C:\IaC\Definitions"

# 创建一个新的环境定义
$envDef = New-InfrastructureDefinition -EnvironmentName "DevTest" -EnvironmentType "Development" -OutputPath $outputPath -Description "开发测试环境"

# 添加网络资源
$subnets = @(
[PSCustomObject]@{ Name = "Frontend"; AddressPrefix = "10.0.1.0/24" },
[PSCustomObject]@{ Name = "Backend"; AddressPrefix = "10.0.2.0/24" },
[PSCustomObject]@{ Name = "Database"; AddressPrefix = "10.0.3.0/24" }
)

$envDef = Add-NetworkResource -InfrastructureDefinition $envDef -NetworkName "DevVNet" -AddressSpace "10.0.0.0/16" -Subnets $subnets -OutputPath $outputPath

# 添加虚拟机资源
$envDef = Add-VMResource -InfrastructureDefinition $envDef -VMName "WebServer01" -Size "Standard_B2s" -OSType "Windows" -OSVersion "2022-Datacenter" -NetworkName "DevVNet" -SubnetName "Frontend" -DependsOn @("DevVNet") -OutputPath $outputPath

$envDef = Add-VMResource -InfrastructureDefinition $envDef -VMName "AppServer01" -Size "Standard_B2s" -OSType "Windows" -OSVersion "2022-Datacenter" -NetworkName "DevVNet" -SubnetName "Backend" -DependsOn @("DevVNet", "WebServer01") -OutputPath $outputPath

$envDef = Add-VMResource -InfrastructureDefinition $envDef -VMName "DbServer01" -Size "Standard_B2ms" -OSType "Windows" -OSVersion "2022-Datacenter" -NetworkName "DevVNet" -SubnetName "Database" -DependsOn @("DevVNet") -OutputPath $outputPath

# 生成部署顺序
$envDef = Set-DeploymentOrder -InfrastructureDefinition $envDef -Validate -OutputPath $outputPath

# 预览部署(WhatIf)
$deploymentPreview = Deploy-Infrastructure -InfrastructureDefinition $envDef -WhatIf -DeploymentLogPath "C:\IaC\Logs"

# 实际部署
$deploymentResult = Deploy-Infrastructure -InfrastructureDefinition $envDef -DeploymentLogPath "C:\IaC\Logs"

这些PowerShell函数提供了一个强大的基础设施即代码解决方案,可以帮助自动化环境部署流程。随着基础设施复杂性的增加,您可以扩展这些函数来支持更多的资源类型和部署场景。结合版本控制系统如Git,这种方法能够确保环境配置的一致性和可重复性,从而提高IT运维的效率和可靠性。