PowerShell 技能连载 - XML 处理技巧

在 PowerShell 中处理 XML 数据是一项常见任务,特别是在配置管理和数据交换场景中。本文将介绍一些实用的 XML 处理技巧。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 创建 XML 文档
$xml = [xml]@"
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="ServerName" value="localhost" />
<add key="Port" value="8080" />
</appSettings>
<database>
<connectionString>Server=localhost;Database=MyDB;Trusted_Connection=True;</connectionString>
</database>
</configuration>
"@

# 访问 XML 节点
Write-Host "`n服务器名称:$($xml.configuration.appSettings.add[0].value)"
Write-Host "端口号:$($xml.configuration.appSettings.add[1].value)"

XML 节点操作:

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
# 创建 XML 节点操作函数
function Update-XMLNode {
param(
[xml]$XmlDocument,
[string]$XPath,
[string]$Value
)

$node = $XmlDocument.SelectSingleNode($XPath)
if ($node) {
$node.InnerText = $Value
Write-Host "已更新节点:$XPath"
}
else {
Write-Host "未找到节点:$XPath"
}
}

# 使用示例
$configPath = "C:\App\config.xml"
$config = [xml](Get-Content $configPath)

Update-XMLNode -XmlDocument $config -XPath "//add[@key='ServerName']/@value" -Value "newserver"
Update-XMLNode -XmlDocument $config -XPath "//add[@key='Port']/@value" -Value "9090"

# 保存更改
$config.Save($configPath)

XML 数据验证:

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
# 创建 XML 验证函数
function Test-XMLValidation {
param(
[string]$XmlPath,
[string]$SchemaPath
)

try {
# 加载 XML 文档
$xml = New-Object System.Xml.XmlDocument
$xml.Load($XmlPath)

# 加载 XML Schema
$schema = New-Object System.Xml.Schema.XmlSchemaSet
$schema.Add("", $SchemaPath)

# 验证 XML
$xml.Schemas = $schema
$xml.Validate($null)

Write-Host "XML 验证成功"
return $true
}
catch {
Write-Host "XML 验证失败:$_"
return $false
}
}

XML 转换:

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
# 创建 XML 转换函数
function Convert-XMLToObject {
param(
[xml]$XmlDocument,
[string]$RootNode
)

$result = @()
$nodes = $XmlDocument.SelectNodes("//$RootNode")

foreach ($node in $nodes) {
$obj = [PSCustomObject]@{}
foreach ($child in $node.ChildNodes) {
$obj | Add-Member -NotePropertyName $child.Name -NotePropertyValue $child.InnerText
}
$result += $obj
}

return $result
}

# 使用示例
$xml = [xml]@"
<?xml version="1.0"?>
<users>
<user>
<name>张三</name>
<age>30</age>
<email>zhangsan@example.com</email>
</user>
<user>
<name>李四</name>
<age>25</age>
<email>lisi@example.com</email>
</user>
</users>
"@

$users = Convert-XMLToObject -XmlDocument $xml -RootNode "user"
$users | Format-Table -AutoSize

一些实用的 XML 处理技巧:

  1. XML 数据合并:

    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
    # 合并多个 XML 文件
    function Merge-XMLFiles {
    param(
    [string[]]$SourceFiles,
    [string]$OutputFile
    )

    $mergedXml = [xml]@"
    <?xml version="1.0" encoding="UTF-8"?>
    <mergedData>
    </mergedData>
    "@

    foreach ($file in $SourceFiles) {
    $xml = [xml](Get-Content $file)
    $root = $xml.DocumentElement

    # 导入节点
    $importedNode = $mergedXml.ImportNode($root, $true)
    $mergedXml.DocumentElement.AppendChild($importedNode)
    }

    # 保存合并后的文件
    $mergedXml.Save($OutputFile)
    Write-Host "已合并 XML 文件到:$OutputFile"
    }
  2. XML 数据过滤:

    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
    # 创建 XML 过滤函数
    function Filter-XMLData {
    param(
    [xml]$XmlDocument,
    [string]$XPath,
    [hashtable]$Conditions
    )

    $nodes = $XmlDocument.SelectNodes($XPath)
    $filteredNodes = @()

    foreach ($node in $nodes) {
    $match = $true
    foreach ($condition in $Conditions.GetEnumerator()) {
    $value = $node.SelectSingleNode($condition.Key).InnerText
    if ($value -ne $condition.Value) {
    $match = $false
    break
    }
    }

    if ($match) {
    $filteredNodes += $node
    }
    }

    return $filteredNodes
    }
  3. XML 数据导出:

    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
    # 导出数据为 XML
    function Export-ToXML {
    param(
    [object[]]$Data,
    [string]$RootNode,
    [string]$OutputFile
    )

    $xml = [xml]@"
    <?xml version="1.0" encoding="UTF-8"?>
    <$RootNode>
    </$RootNode>
    "@

    foreach ($item in $Data) {
    $node = $xml.CreateElement($item.GetType().Name)

    foreach ($prop in $item.PSObject.Properties) {
    $child = $xml.CreateElement($prop.Name)
    $child.InnerText = $prop.Value
    $node.AppendChild($child)
    }

    $xml.DocumentElement.AppendChild($node)
    }

    # 保存 XML 文件
    $xml.Save($OutputFile)
    Write-Host "已导出数据到:$OutputFile"
    }

这些技巧将帮助您更有效地处理 XML 数据。记住,在处理 XML 时,始终要注意数据的完整性和格式正确性。同时,建议在处理大型 XML 文件时使用流式处理方式,以提高性能。

PowerShell 技能连载 - OpenAI 集成

在人工智能时代,将OpenAI的强大能力集成到PowerShell中可以为系统管理带来革命性的提升。本文将介绍如何使用PowerShell构建一个与OpenAI集成的智能管理系统,包括自然语言处理、代码生成和智能分析等功能。

自然语言处理

首先,让我们创建一个用于管理自然语言处理的函数:

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 Process-NaturalLanguage {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ProcessID,

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

[Parameter()]
[ValidateSet("Text", "Code", "Command")]
[string]$ProcessMode = "Text",

[Parameter()]
[hashtable]$ProcessConfig,

[Parameter()]
[string]$LogPath
)

try {
$processor = [PSCustomObject]@{
ProcessID = $ProcessID
StartTime = Get-Date
ProcessStatus = @{}
Results = @{}
Errors = @()
}

# 获取处理配置
$config = Get-ProcessConfig -ProcessID $ProcessID

# 管理处理
foreach ($type in $ProcessTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Results = @{}
Errors = @()
}

# 应用处理配置
$typeConfig = Apply-ProcessConfig `
-Config $config `
-Type $type `
-Mode $ProcessMode `
-Settings $ProcessConfig

$status.Config = $typeConfig

# 处理自然语言
$results = Process-OpenAIRequest `
-Type $type `
-Config $typeConfig

$status.Results = $results
$processor.Results[$type] = $results

# 检查处理错误
$errors = Check-ProcessErrors `
-Results $results `
-Config $typeConfig

$status.Errors = $errors
$processor.Errors += $errors

# 更新处理状态
if ($errors.Count -gt 0) {
$status.Status = "Error"
}
else {
$status.Status = "Success"
}

$processor.ProcessStatus[$type] = $status
}

# 记录处理日志
if ($LogPath) {
$processor | ConvertTo-Json -Depth 10 | Out-File -FilePath $LogPath
}

# 更新处理器状态
$processor.EndTime = Get-Date

return $processor
}
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
function Generate-PowerShellCode {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$GenerationID,

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

[Parameter()]
[ValidateSet("Function", "Module", "Script")]
[string]$GenerationMode = "Function",

[Parameter()]
[hashtable]$GenerationConfig,

[Parameter()]
[string]$ReportPath
)

try {
$generator = [PSCustomObject]@{
GenerationID = $GenerationID
StartTime = Get-Date
GenerationStatus = @{}
Code = @{}
Validation = @()
}

# 获取生成配置
$config = Get-GenerationConfig -GenerationID $GenerationID

# 管理生成
foreach ($type in $GenerationTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Code = @{}
Validation = @()
}

# 应用生成配置
$typeConfig = Apply-GenerationConfig `
-Config $config `
-Type $type `
-Mode $GenerationMode `
-Settings $GenerationConfig

$status.Config = $typeConfig

# 生成PowerShell代码
$code = Generate-OpenAICode `
-Type $type `
-Config $typeConfig

$status.Code = $code
$generator.Code[$type] = $code

# 验证生成代码
$validation = Validate-GeneratedCode `
-Code $code `
-Config $typeConfig

$status.Validation = $validation
$generator.Validation += $validation

# 更新生成状态
if ($validation.Success) {
$status.Status = "Valid"
}
else {
$status.Status = "Invalid"
}

$generator.GenerationStatus[$type] = $status
}

# 生成报告
if ($ReportPath) {
$report = Generate-CodeReport `
-Generator $generator `
-Config $config

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

# 更新生成器状态
$generator.EndTime = Get-Date

return $generator
}
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
function Analyze-IntelligentData {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$AnalysisID,

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

[Parameter()]
[ValidateSet("Pattern", "Prediction", "Recommendation")]
[string]$AnalysisMode = "Pattern",

[Parameter()]
[hashtable]$AnalysisConfig,

[Parameter()]
[string]$ReportPath
)

try {
$analyzer = [PSCustomObject]@{
AnalysisID = $AnalysisID
StartTime = Get-Date
AnalysisStatus = @{}
Insights = @{}
Actions = @()
}

# 获取分析配置
$config = Get-AnalysisConfig -AnalysisID $AnalysisID

# 管理分析
foreach ($type in $AnalysisTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Insights = @{}
Actions = @()
}

# 应用分析配置
$typeConfig = Apply-AnalysisConfig `
-Config $config `
-Type $type `
-Mode $AnalysisMode `
-Settings $AnalysisConfig

$status.Config = $typeConfig

# 分析智能数据
$insights = Analyze-OpenAIData `
-Type $type `
-Config $typeConfig

$status.Insights = $insights
$analyzer.Insights[$type] = $insights

# 生成分析动作
$actions = Generate-AnalysisActions `
-Insights $insights `
-Config $typeConfig

$status.Actions = $actions
$analyzer.Actions += $actions

# 更新分析状态
if ($actions.Count -gt 0) {
$status.Status = "Actionable"
}
else {
$status.Status = "NoAction"
}

$analyzer.AnalysisStatus[$type] = $status
}

# 生成报告
if ($ReportPath) {
$report = Generate-AnalysisReport `
-Analyzer $analyzer `
-Config $config

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

# 更新分析器状态
$analyzer.EndTime = Get-Date

return $analyzer
}
catch {
Write-Error "智能分析失败:$_"
return $null
}
}

使用示例

以下是如何使用这些函数来集成OpenAI的示例:

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
# 处理自然语言
$processor = Process-NaturalLanguage -ProcessID "PROCESS001" `
-ProcessTypes @("Text", "Code", "Command") `
-ProcessMode "Text" `
-ProcessConfig @{
"Text" = @{
"Model" = "gpt-4"
"MaxTokens" = 1000
"Temperature" = 0.7
"Retention" = 7
}
"Code" = @{
"Model" = "gpt-4"
"MaxTokens" = 2000
"Temperature" = 0.3
"Retention" = 7
}
"Command" = @{
"Model" = "gpt-4"
"MaxTokens" = 500
"Temperature" = 0.5
"Retention" = 7
}
} `
-LogPath "C:\Logs\nlp_processing.json"

# 生成PowerShell代码
$generator = Generate-PowerShellCode -GenerationID "GENERATION001" `
-GenerationTypes @("Function", "Module", "Script") `
-GenerationMode "Function" `
-GenerationConfig @{
"Function" = @{
"Model" = "gpt-4"
"MaxTokens" = 2000
"Temperature" = 0.3
"Validation" = $true
}
"Module" = @{
"Model" = "gpt-4"
"MaxTokens" = 4000
"Temperature" = 0.3
"Validation" = $true
}
"Script" = @{
"Model" = "gpt-4"
"MaxTokens" = 3000
"Temperature" = 0.3
"Validation" = $true
}
} `
-ReportPath "C:\Reports\code_generation.json"

# 分析智能数据
$analyzer = Analyze-IntelligentData -AnalysisID "ANALYSIS001" `
-AnalysisTypes @("Pattern", "Prediction", "Recommendation") `
-AnalysisMode "Pattern" `
-AnalysisConfig @{
"Pattern" = @{
"Model" = "gpt-4"
"MaxTokens" = 1000
"Temperature" = 0.7
"Report" = $true
}
"Prediction" = @{
"Model" = "gpt-4"
"MaxTokens" = 1000
"Temperature" = 0.7
"Report" = $true
}
"Recommendation" = @{
"Model" = "gpt-4"
"MaxTokens" = 1000
"Temperature" = 0.7
"Report" = $true
}
} `
-ReportPath "C:\Reports\intelligent_analysis.json"

最佳实践

  1. 实施自然语言处理
  2. 生成PowerShell代码
  3. 分析智能数据
  4. 保持详细的处理记录
  5. 定期进行代码验证
  6. 实施分析策略
  7. 建立错误处理
  8. 保持系统文档更新

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-DeviceHealthCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$DeviceName
)

$healthReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Device = $DeviceName
TPMEnabled = $false
SecureBoot = $false
AntivirusStatus = 'Unknown'
ComplianceScore = 0
}

try {
# 检查TPM状态
$tpm = Get-Tpm -ErrorAction Stop
$healthReport.TPMEnabled = $tpm.TpmPresent

# 验证安全启动状态
$healthReport.SecureBoot = Confirm-SecureBootUEFI

# 获取反病毒状态
$avStatus = Get-MpComputerStatus
$healthReport.AntivirusStatus = $avStatus.AMServiceEnabled ? 'Active' : 'Inactive'

# 计算合规分数
$compliance = 0
if($healthReport.TPMEnabled) { $compliance += 30 }
if($healthReport.SecureBoot) { $compliance += 30 }
if($healthReport.AntivirusStatus -eq 'Active') { $compliance += 40 }
$healthReport.ComplianceScore = $compliance
}
catch {
Write-Warning "设备健康检查失败: $_"
}

$healthReport | Export-Clixml -Path "$env:TEMP/DeviceHealth_$DeviceName.xml"
return $healthReport
}

核心功能

  1. TPM芯片状态验证
  2. 安全启动模式检测
  3. 反病毒服务状态监控
  4. 自动化合规评分

应用场景

  • 零信任架构准入控制
  • 远程办公设备安全审计
  • 合规性基线验证
  • 安全事件响应前置检查

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 技能连载 - 图像处理技巧

在 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
# 创建图像信息获取函数
function Get-ImageInfo {
param(
[string]$ImagePath
)

try {
# 使用 ImageMagick 获取图像信息
$magick = "magick"
$info = & $magick identify -format "%wx%h,%b,%m" $ImagePath

$dimensions, $size, $format = $info -split ","
$width, $height = $dimensions -split "x"

return [PSCustomObject]@{
FileName = Split-Path $ImagePath -Leaf
Width = [int]$width
Height = [int]$height
Size = [math]::Round([double]$size / 1KB, 2)
Format = $format
}
}
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 Convert-ImageFormat {
param(
[string]$InputPath,
[string]$OutputPath,
[ValidateSet("jpg", "png", "bmp", "gif")]
[string]$TargetFormat,
[ValidateSet("high", "medium", "low")]
[string]$Quality = "medium"
)

try {
$magick = "magick"
$qualitySettings = @{
"high" = "-quality 100"
"medium" = "-quality 80"
"low" = "-quality 60"
}

$command = "$magick `"$InputPath`" $($qualitySettings[$Quality]) `"$OutputPath`""
Invoke-Expression $command

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
# 创建图像缩放函数
function Resize-Image {
param(
[string]$InputPath,
[string]$OutputPath,
[int]$Width,
[int]$Height,
[ValidateSet("fit", "fill", "crop")]
[string]$Mode = "fit"
)

try {
$magick = "magick"
$resizeSettings = @{
"fit" = "-resize ${Width}x${Height}>"
"fill" = "-resize ${Width}x${Height}!"
"crop" = "-resize ${Width}x${Height}^ -gravity center -extent ${Width}x${Height}"
}

$command = "$magick `"$InputPath`" $($resizeSettings[$Mode]) `"$OutputPath`""
Invoke-Expression $command

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

try {
$magick = "magick"
$effectSettings = @{
"grayscale" = "-colorspace gray"
"sepia" = "-sepia-tone 80%"
"blur" = "-blur 0x$($Parameters.Radius)"
"sharpen" = "-sharpen 0x$($Parameters.Amount)"
}

$command = "$magick `"$InputPath`" $($effectSettings[$Effect]) `"$OutputPath`""
Invoke-Expression $command

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
# 创建图像批量处理函数
function Process-ImageBatch {
param(
[string]$InputFolder,
[string]$OutputFolder,
[scriptblock]$ProcessScript
)

try {
if (-not (Test-Path $OutputFolder)) {
New-Item -ItemType Directory -Path $OutputFolder | Out-Null
}

Get-ChildItem -Path $InputFolder -Include *.jpg,*.png,*.bmp,*.gif -Recurse | ForEach-Object {
$outputPath = Join-Path $OutputFolder $_.Name
& $ProcessScript $_.FullName $outputPath
}

Write-Host "批量处理完成"
}
catch {
Write-Host "批量处理失败:$_"
}
}

这些技巧将帮助您更有效地处理图像文件。记住,在处理图像时,始终要注意文件格式的兼容性和图像质量。同时,建议在处理大型图像文件时使用流式处理方式,以提高性能。

PowerShell变量作用域深度解析

变量作用域层级

1
2
3
4
5
6
7
8
9
10
11
12
# 全局作用域示例
$Global:config = 'ServerConfig'

function Show-Config {
# 局部作用域变量
$localVar = 'LocalValue'
Write-Host "全局变量: $Global:config"
Write-Host "局部变量: $localVar"
}

Show-Config
Write-Host "外部访问: $localVar" # 此处会报错

作用域修饰符对比

修饰符 可见范围 生命周期
Global 所有作用域 会话结束
Local 当前作用域 代码块结束
Script 脚本文件内 脚本执行结束
Private 当前作用域内部 代码块结束

最佳实践

  1. 避免过度使用全局变量
  2. 函数参数优先于外部变量引用
  3. 使用$script:访问脚本级变量
  4. 重要变量显式声明作用域

调试技巧

1
2
3
4
5
# 查看当前作用域变量
Get-Variable -Scope 1

# 跨作用域修改变量
Set-Variable -Name config -Value 'NewConfig' -Scope 2

PowerShell 技能连载 - 批量检测服务器端口

使用 PowerShell 可以快速地检测服务器端口。以下是一个示例:

1
80, 443 | % { Test-Connection -ComputerName www.microsoft.com -TcpPort $_ }

在 PowerShell 提示符下运行这段代码,那么它将尝试连接到一个名为 www.microsoft.com 的计算机,并尝试连接端口 80 和 443。如果网络连接正常,那么您将会看到类似下面的输出:

1
2
True
True

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

在 PowerShell 中处理 JSON 数据变得越来越常见,特别是在与 Web API 交互或处理配置文件时。本文将介绍一些实用的 JSON 处理技巧。

首先,让我们看看如何创建和转换 JSON 数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 创建 JSON 对象
$userData = @{
name = "张三"
age = 30
hobbies = @("读书", "编程", "摄影")
contact = @{
email = "zhangsan@example.com"
phone = "123-456-7890"
}
}

# 转换为 JSON 字符串
$jsonString = $userData | ConvertTo-Json -Depth 10
Write-Host "JSON 字符串:"
Write-Host $jsonString

# 从 JSON 字符串转换回对象
$object = $jsonString | ConvertFrom-Json
Write-Host "`n转换回对象:"
$object | Format-List

处理复杂的 JSON 数据时,我们可以使用自定义对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 创建自定义对象并转换为 JSON
$customObject = [PSCustomObject]@{
id = 1
title = "PowerShell 技巧"
author = "李四"
tags = @("PowerShell", "自动化", "脚本")
metadata = @{
created = Get-Date
version = "1.0.0"
}
}

# 转换为 JSON 并保存到文件
$customObject | ConvertTo-Json -Depth 10 | Set-Content "article.json"

# 从文件读取 JSON
$loadedData = Get-Content "article.json" | ConvertFrom-Json

处理 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
# 处理 API 响应
$apiResponse = @'
{
"status": "success",
"data": {
"users": [
{
"id": 1,
"name": "王五",
"role": "admin"
},
{
"id": 2,
"name": "赵六",
"role": "user"
}
],
"total": 2
}
}
'@

# 解析 JSON 并访问嵌套数据
$response = $apiResponse | ConvertFrom-Json
$adminUsers = $response.data.users | Where-Object { $_.role -eq "admin" }
Write-Host "管理员用户:"
$adminUsers | Format-Table

处理大型 JSON 文件时的性能优化:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 使用流式处理大型 JSON 文件
$jsonStream = [System.IO.File]::OpenRead("large-data.json")
$reader = [System.IO.StreamReader]::new($jsonStream)
$jsonText = $reader.ReadToEnd()
$reader.Close()
$jsonStream.Close()

# 使用 System.Text.Json 进行高性能解析
Add-Type -AssemblyName System.Text.Json
$jsonDoc = [System.Text.Json.JsonDocument]::Parse($jsonText)

# 访问特定属性
$value = $jsonDoc.RootElement.GetProperty("specificField").GetString()

一些实用的 JSON 处理技巧:

  1. 使用 -Compress 参数创建紧凑的 JSON:

    1
    $data | ConvertTo-Json -Compress
  2. 处理日期时间格式:

    1
    2
    3
    $dateObject = @{
    timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
    } | ConvertTo-Json
  3. 验证 JSON 格式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function Test-JsonFormat {
    param([string]$JsonString)
    try {
    $null = $JsonString | ConvertFrom-Json
    return $true
    }
    catch {
    return $false
    }
    }

这些技巧将帮助您更有效地处理 JSON 数据。记住,在处理敏感数据时,始终要注意数据安全性,并考虑使用适当的加密方法。

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

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

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

# 组件哈希校验
Get-ChildItem $ScanPath -Recurse -Include *.dll,*.exe,*.psm1 | ForEach-Object {
$fileHash = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$signature = Get-AuthenticodeSignature $_.FullName

$component = [PSCustomObject]@{
FileName = $_.Name
FilePath = $_.FullName
SHA256 = $fileHash
IsSigned = $signature.Status -eq 'Valid'
Publisher = $signature.SignerCertificate.Subject
}
$report.ScannedComponents += $component

if (-not $component.IsSigned) {
$report.SecurityFindings += [PSCustomObject]@{
Severity = 'High'
Description = "未签名的组件: $($_.Name)"
Recommendation = "要求供应商提供数字签名版本或验证组件来源"
}
}
}

# 依赖包漏洞扫描
$nugetPackages = Get-ChildItem $ScanPath -Recurse -Include packages.config
$nugetPackages | ForEach-Object {
[xml]$config = Get-Content $_.FullName
$config.packages.package | ForEach-Object {
$cveData = Invoke-RestMethod "https://api.cvecheck.org/v1/search?id=$($_.id)"
if ($cveData.vulnerabilities | Where-Object { $_.severity -ge $SeverityLevel }) {
$report.SecurityFindings += [PSCustomObject]@{
Severity = $SeverityLevel
Description = "存在漏洞的依赖包: $($_.id) v$($_.version)"
Recommendation = "升级到最新安全版本 $($cveData.latestVersion)"
}
}
}
}

$report | Export-Csv -Path "$ScanPath\SupplyChainReport_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
return $report
}

核心功能

  1. 软件组件供应链安全扫描
  2. 依赖包漏洞自动化检测
  3. 数字签名验证机制
  4. CVE漏洞数据库集成

典型应用场景

  • 开发环境第三方组件安全检查
  • 软件构建流水线安全审计
  • 供应商交付物合规验证
  • 企业软件资产安全基线报告生成

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
function Invoke-DeviceHealthCheck {
param(
[string[]]$ComputerNames = $env:COMPUTERNAME
)

$securityBaseline = @{
SecureBootEnabled = $true
TPMPresent = $true
BitLockerStatus = 'FullyEncrypted'
AntivirusStatus = 'Enabled'
FirewallProfile = 'Domain'
}

$results = @()

foreach ($computer in $ComputerNames) {
try {
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer
$tpm = Get-CimInstance -ClassName Win32_Tpm -ComputerName $computer -ErrorAction Stop
$bitlocker = Get-BitLockerVolume -MountPoint $osInfo.SystemDrive -ErrorAction Stop

$healthStatus = [PSCustomObject]@{
ComputerName = $computer
LastBootTime = $osInfo.LastBootUpTime
SecureBoot = [bool](Confirm-SecureBootUEFI)
TPMVersion = $tpm.SpecVersion
BitLockerProtection = $bitlocker.ProtectionStatus
DefenderStatus = (Get-MpComputerStatus).AntivirusEnabled
FirewallStatus = (Get-NetFirewallProfile -Name Domain).Enabled
ComplianceScore = 0
}

# 计算合规分数
$healthStatus.ComplianceScore = [math]::Round((
($healthStatus.SecureBoot -eq $securityBaseline.SecureBootEnabled) +
($healthStatus.TPMVersion -match '2.0') +
($healthStatus.BitLockerProtection -eq 'On') +
($healthStatus.DefenderStatus -eq $true) +
($healthStatus.FirewallStatus -eq $true)
) / 5 * 100, 2)

$results += $healthStatus
}
catch {
Write-Warning "$computer 健康检查失败: $_"
}
}

$results | Format-Table -AutoSize
}

核心功能:

  1. 自动化验证设备安全基线配置
  2. 检测TPM 2.0和SecureBoot状态
  3. 评估BitLocker加密状态
  4. 生成设备合规性评分

应用场景:

  • 零信任网络接入前检查
  • 远程办公设备安全审计
  • 合规性自动化报告生成