PowerShell 技能连载 - Azure多云成本优化实践

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
function Get-AzureCostAnalysis {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,
[datetime]$StartDate = (Get-Date).AddDays(-30)
)

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

foreach ($subId in $SubscriptionIds) {
Set-AzContext -SubscriptionId $subId | Out-Null

# 获取资源消耗数据
$resources = Get-AzResource | Where-Object {
$_.ResourceType -notin @('Microsoft.Resources/deployments','Microsoft.Resources/subscriptions')
}

$resourceGroups = $resources | Group-Object ResourceGroupName
foreach ($rg in $resourceGroups) {
$costData = Get-AzConsumptionUsageDetail -StartDate $StartDate -EndDate (Get-Date) -ResourceGroup $rg.Name

$report.ResourceAnalysis += [PSCustomObject]@{
Subscription = $subId
ResourceGroup = $rg.Name
TotalCost = ($costData | Measure-Object PretaxCost -Sum).Sum
UnderutilizedVMs = $rg.Group.Where{ $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' }.Count
}
}
}

# 生成优化建议
$report.ResourceAnalysis | ForEach-Object {
if ($_.UnderutilizedVMs -gt 5) {
$report.CostRecommendations += [PSCustomObject]@{
Recommendation = "调整资源组 $($_.ResourceGroup) 中未充分利用的VM规模"
PotentialSavings = "预计节省 $([math]::Round($_.TotalCost * 0.3)) 美元"
}
}
}

$report | Export-Excel -Path "$env:TEMP/AzureCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $report
}

核心功能

  1. 跨订阅资源消耗分析
  2. 闲置VM资源自动识别
  3. 成本节约潜力预测
  4. Excel报告自动生成

典型应用场景

  • 企业多云成本可视化管理
  • FinOps实践中的资源优化
  • 预算执行情况跟踪
  • 云服务商比价数据支持

PowerShell 技能连载 - Azure AD安全审计自动化

在云身份管理日益重要的今天,定期安全审计成为保障企业数字资产的关键。本文演示如何通过PowerShell自动执行Azure AD安全配置检测,实现实时安全态势监控。

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
function Invoke-AzureADSecurityAudit {
param(
[string]$TenantId,
[switch]$ExportReport
)

try {
# 连接Azure AD
Connect-AzureAD -TenantId $TenantId | Out-Null

# 安全基线检测
$results = @(
[PSCustomObject]@{
CheckItem = '多重认证状态'
Result = (Get-AzureADMSAuthorizationPolicy).DefaultUserRolePermissions.AllowedToCreateApps
},
[PSCustomObject]@{
CheckItem = '旧协议支持状态'
Result = (Get-AzureADDirectorySetting | Where-Object {$_.DisplayName -eq 'OrganizationProperties'}).Values
}
)

# 生成报告
if ($ExportReport) {
$results | Export-Csv -Path "./SecurityAudit_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
}

return $results
}
catch {
Write-Error "审计失败:$_"
}
finally {
Disconnect-AzureAD
}
}

实现原理分析:

  1. 通过AzureAD模块实现与云身份服务的认证连接
  2. 检测关键安全配置项包括MFA实施状态和旧版协议支持情况
  3. 支持CSV报告导出功能便于存档分析
  4. 自动清理会话确保操作安全性
  5. 结构化返回结果便于后续处理

该脚本将原本需要人工操作的审计流程自动化,特别适合需要持续合规监控的金融和医疗行业应用场景。

PowerShell 技能连载 - 基于Azure Functions的无服务器安全检测

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
function Invoke-SecurityScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,

[ValidateSet('Critical','High','Medium')]
[string]$SeverityLevel = 'High'
)

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

# 获取Azure安全中心警报
$alerts = Get-AzSecurityAlert -ResourceGroupName $ResourceGroup |
Where-Object { $_.Severity -eq $SeverityLevel }

# 自动化响应流程
$alerts | ForEach-Object {
$securityReport.ScannedResources += [PSCustomObject]@{
ResourceID = $_.ResourceId
AlertType = $_.AlertType
CompromiseEntity = $_.CompromisedEntity
}

# 触发自动化修复动作
if($_.AlertType -eq 'UnusualResourceDeployment') {
Start-AzResourceDelete -ResourceId $_.ResourceId -Force
$securityReport.SecurityFindings += [PSCustomObject]@{
Action = 'DeletedSuspiciousResource'
ResourceID = $_.ResourceId
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
}
}
}

# 生成安全态势报告
$securityReport | ConvertTo-Json -Depth 3 |
Out-File -FilePath "$env:TEMP/AzureSecReport_$(Get-Date -Format yyyyMMdd).json"
return $securityReport
}

核心功能

  1. 实时获取Azure安全中心高等级警报
  2. 异常资源部署自动隔离机制
  3. JSON格式安全态势报告生成
  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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function Get-CloudCostReport {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,

[ValidateSet('Daily','Monthly')]
[string]$Granularity = 'Monthly'
)

$costReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
TotalCost = 0
ServiceBreakdown = @{}
OptimizationSuggestions = @()
}

try {
# 获取跨云成本数据
$costData = $SubscriptionIds | ForEach-Object {
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$_/providers/Microsoft.CostManagement/query?api-version=2023-03-01" \
-Headers @{ Authorization = "Bearer $env:AZURE_TOKEN" } \
-Body (@{
type = "ActualCost"
timeframe = "MonthToDate"
dataset = @{
aggregation = @{
totalCost = @{
name = "Cost"
function = "Sum"
}
}
grouping = @(
@{
type = "Dimension"
name = "ServiceName"
}
)
}
} | ConvertTo-Json)
}

# 分析成本结构
$costReport.TotalCost = ($costData.properties.rows | Measure-Object -Property [0] -Sum).Sum
$costReport.ServiceBreakdown = $costData.properties.rows |
Group-Object { $_[1] } -AsHashTable |
ForEach-Object { @{$_.Key = [math]::Round($_.Value[0],2)} }

# 生成优化建议
$costData.properties.rows | Where-Object { $_[0] -gt 1000 } | ForEach-Object {
$costReport.OptimizationSuggestions += [PSCustomObject]@{
Service = $_[1]
Cost = $_[0]
Recommendation = "考虑预留实例或自动缩放配置"
}
}
}
catch {
Write-Error "成本数据获取失败: $_"
}

# 生成Excel格式报告
$costReport | Export-Excel -Path "$env:TEMP/CloudCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $costReport
}

核心功能

  1. 跨云成本数据聚合分析
  2. 服务维度费用结构分解
  3. 智能优化建议生成
  4. Excel格式报告输出

应用场景

  • 多云环境成本监控
  • 预算超支预警
  • 资源使用效率优化
  • 财务部门合规报告

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流水线安全卡点集成

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
function Invoke-HybridIaC {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Azure','AWS','OnPrem')]
[string[]]$Environments,

[string]$DscConfigPath = '$PSScriptRoot/dsc'
)

$deploymentReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
AppliedConfigs = @()
ComplianceStatus = @{}
CrossPlatformIssues = @()
}

try {
# 应用Terraform基础设施
$Environments | ForEach-Object {
if ($PSCmdlet.ShouldProcess("Deploy $_ resources")) {
terraform -chdir="$DscConfigPath/terraform/$_" apply -auto-approve
}
}

# 执行DSC配置
$Environments | ForEach-Object {
$dscConfig = Get-ChildItem "$DscConfigPath/$_" -Filter *.ps1
$dscConfig | ForEach-Object {
$job = Start-Job -ScriptBlock {
param($config)
& $config.FullName
} -ArgumentList $_
$deploymentReport.AppliedConfigs += $job | Wait-Job | Receive-Job
}
}

# 验证混合云合规性
$deploymentReport.ComplianceStatus = $Environments | ForEach-Object {
$status = Test-DscConfiguration -CimSession (New-CimSession -ComputerName $_)
@{$_ = $status.InDesiredState ? 'Compliant' : 'Non-Compliant'}
}
}
catch {
Write-Error "混合云部署失败: $_"
terraform -chdir="$DscConfigPath/terraform" destroy -auto-approve
}

# 生成统一部署报告
$deploymentReport | Export-Clixml -Path "$env:TEMP/HybridIaC_Report_$(Get-Date -Format yyyyMMdd).xml"
return $deploymentReport
}

核心功能

  1. 多环境Terraform编排
  2. DSC配置跨平台应用
  3. 混合云合规性验证
  4. 原子化作业执行

应用场景

  • 混合云环境统一管理
  • 配置漂移自动修复
  • 跨云平台灾备部署
  • 基础设施合规审计

PowerShell 技能连载 - Microsoft Graph API 集成自动化

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
function Manage-Office365Resources {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('User','Team')]
[string]$ResourceType,

[string]$DisplayName
)

$managementReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Operations = @()
SuccessRate = 0
LicenseDetails = @{}
}

try {
# 获取Graph API访问令牌
$token = Get-MsalToken -ClientId $env:AZURE_CLIENT_ID -TenantId $env:AZURE_TENANT_ID

# 资源操作逻辑
switch ($ResourceType) {
'User' {
$userParams = @{
Method = 'POST'
Uri = "https://graph.microsoft.com/v1.0/users"
Headers = @{ Authorization = "Bearer $($token.AccessToken)" }
Body = @{
accountEnabled = $true
displayName = $DisplayName
mailNickname = $DisplayName.Replace(' ','').ToLower()
userPrincipalName = "$($DisplayName.Replace(' ',''))@$env:AZURE_DOMAIN"
passwordProfile = @{
forceChangePasswordNextSignIn = $true
password = [System.Convert]::ToBase64String((1..12 | ForEach-Object { [char](Get-Random -Minimum 33 -Maximum 126) }))
}
} | ConvertTo-Json
}
$response = Invoke-RestMethod @userParams
$managementReport.Operations += [PSCustomObject]@{
Type = 'UserCreated'
ID = $response.id
}
}

'Team' {
$teamParams = @{
Method = 'POST'
Uri = "https://graph.microsoft.com/v1.0/teams"
Headers = @{ Authorization = "Bearer $($token.AccessToken)" }
Body = @{
"template@odata.bind" = "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"
displayName = $DisplayName
description = "Automatically created team"
} | ConvertTo-Json
}
$response = Invoke-RestMethod @teamParams
$managementReport.Operations += [PSCustomObject]@{
Type = 'TeamProvisioned'
ID = $response.id
}
}
}

# 获取许可证信息
$licenseData = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/subscribedSkus" \
-Headers @{ Authorization = "Bearer $($token.AccessToken)" }
$managementReport.LicenseDetails = $licenseData.value |
Group-Object skuPartNumber -AsHashTable |
ForEach-Object { @{$_.Key = $_.Value.consumedUnits} }

# 计算成功率
$managementReport.SuccessRate = ($managementReport.Operations.Count / 1) * 100
}
catch {
Write-Error "资源管理失败: $_"
}

# 生成管理报告
$managementReport | Export-Clixml -Path "$env:TEMP/GraphReport_$(Get-Date -Format yyyyMMdd).xml"
return $managementReport
}

核心功能

  1. Azure AD用户自动化创建
  2. Microsoft Teams团队自动部署
  3. 许可证使用情况监控
  4. XML格式管理报告

应用场景

  • 企业用户生命周期管理
  • 团队协作环境快速部署
  • 许可证使用效率分析
  • 合规审计数据准备

PowerShell 技能连载 - Azure Functions自动化管理

在无服务器架构日益普及的今天,Azure Functions作为事件驱动的计算服务广受欢迎。本文将演示如何通过PowerShell实现Functions的自动化部署与监控,帮助运维人员提升云端资源管理效率。

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 Manage-AzureFunction {
param(
[ValidateSet('Create','Update','Remove')]
[string]$Action,
[string]$FunctionName,
[string]$ResourceGroup
)

try {
# 身份验证检查
if (-not (Get-AzContext)) {
Connect-AzAccount -UseDeviceAuthentication
}

switch ($Action) {
'Create' {
New-AzFunctionApp -Name $FunctionName -ResourceGroupName $ResourceGroup `
-Runtime PowerShell -StorageAccount (Get-AzStorageAccount -ResourceGroupName $ResourceGroup).StorageAccountName `
-FunctionsVersion 4 -Location 'EastUS'
}
'Update' {
Publish-AzWebApp -ResourceGroupName $ResourceGroup -Name $FunctionName `
-ArchivePath (Compress-Archive -Path ./src -DestinationPath function.zip -Force)
}
'Remove' {
Remove-AzFunctionApp -Name $FunctionName -ResourceGroupName $ResourceGroup -Force
}
}

# 获取运行状态
$status = Get-AzFunctionApp -Name $FunctionName -ResourceGroupName $ResourceGroup
Write-Host "操作成功:$($status.State)"
}
catch {
Write-Error "操作失败:$_"
}
}

实现原理分析:

  1. 通过Azure PowerShell模块实现与云端的认证交互
  2. 参数验证机制确保操作类型合法性
  3. 支持创建/更新/删除三大核心操作的生命周期管理
  4. 部署时自动压缩源代码为ZIP包进行上传
  5. 操作完成后实时获取并返回函数运行状态

该脚本将原本需要多次点击门户的操作简化为单条命令,特别适合需要批量管理多个函数应用的DevOps场景。

PowerShell 技能连载 - 云存储自动化备份方案

在混合云架构中,数据保护是业务连续性的关键。本文演示如何通过PowerShell实现本地数据到云端存储的自动化备份,支持Azure Blob和AWS S3两种主流云存储方案。

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
function Start-CloudBackup {
param(
[string]$LocalPath,
[ValidateSet('Azure','AWS')]
[string]$CloudProvider,
[string]$ContainerName
)

try {
# 压缩本地数据
$backupFile = "$env:TEMP\backup_$(Get-Date -Format yyyyMMdd).zip"
Compress-Archive -Path $LocalPath -DestinationPath $backupFile

# 执行云上传
switch ($CloudProvider) {
'Azure' {
az storage blob upload --account-name $env:AZURE_STORAGE_ACCOUNT \
--container $ContainerName \
--file $backupFile \
--auth-mode key
}
'AWS' {
Write-S3Object -BucketName $ContainerName \
-File $backupFile \
-Region $env:AWS_REGION
}
}

# 验证备份
$checksum = (Get-FileHash $backupFile).Hash
Write-Host "备份完成,校验码:$checksum"
}
catch {
Write-Error "备份失败:$_"
}
finally {
Remove-Item $backupFile -ErrorAction SilentlyContinue
}
}

实现原理分析:

  1. 采用标准化ZIP格式进行数据压缩打包
  2. 通过云服务商CLI工具实现混合云上传
  3. 哈希校验机制确保备份数据完整性
  4. 临时文件自动清理保障存储空间
  5. 异常处理覆盖网络中断和权限问题

该脚本将备份操作从手动执行转为计划任务驱动,特别适合需要定期保护关键业务数据的金融和电商场景。

PowerShell 技术 QQ 群