PowerShell 技能连载 - 针对Windows服务器的4种强大的PowerShell安全技术

简介

在不断发展的网络安全领域中,加固您的Windows服务器不仅是最佳实践,而且是必要的。PowerShell凭借其多功能性和自动化能力,在确保服务器安全的神奇旅程中成为我们可靠的魔杖。让我们讨论一下4种PowerShell安全技术,这将有助于实现我们的目标。

PowerShell安全性: 使用PowerShell进行审计

使用POSH-Sysmon配置Sysmon

Sysmon: 沉默的哨兵

由微软开发的Sysmon是一个强大的工具,用于监视系统并添加细粒度事件以便即使在重启后也能被跟踪。

这就像拥有一把神奇的放大镜,可以揭示服务器上隐藏的活动。

为什么使用POSH-Sysmon?

POSH-Sysmon是一个简化配置Sysmon 的PowerShell脚本。

它让您可以轻松地使用PowerShell创建和管理 Sysinternals Sysmon v2.0 配置文件。

通过Sysmon,您可以跟踪与进程创建、网络连接、注册表更改等相关的事件。

示例: 检测凭证提取尝试

要追踪最关键的事件之一——恶意进程尝试从内存中提取凭据时,

请使用 ProcessAccess 过滤器来检测Local Security Authority Subsystem Service (LSASS) 中此类尝试:

1
Get-WinEvent -LogName 'Microsoft-Windows-Sysmon/Operational' | Where-Object {$_.EventID -eq 10 -and $_.Message -like '*LSASS*'}

强化您的电子邮件堡垒:客户端规则转发阻止控制

为什么这很重要?

攻击者经常利用Office 365,在Outlook中设置静默规则,将敏感电子邮件转发到他们的账户。

通过启用客户端规则转发阻止控制来加强您的电子邮件安全性。

PowerShell操作:

使用PowerShell启用转发阻止:

1
Set-OrganizationConfig -RulesQuota 0

使用DSC进行PowerShell安全配置

什么是PowerShell DSC?

期望状态配置(DSC)就像一种魔法咒语,确保您的服务器保持安全配置。

它允许您定义和强制执行Windows服务器的期望状态。

示例:根据CIS基准进行安全配置

使用PowerShell DSC根据CIS Microsoft Windows Server 2019或Azure Secure Center Baseline for Windows Server 2016等基准应用安全配置。

您的DSC代码成为了您的护身符:

1
2
3
4
5
6
7
8
9
Configuration SecureServer {
Import-DscResource -ModuleName SecurityPolicyDsc
Node 'localhost' {
SecurityPolicy 'Audit - Audit account logon events' {
PolicySetting = 'Success,Failure'
}
# 更多安全设置在此处...
}
}

HardeningKitty:Windows配置的猫护卫

小猫在忙什么?

HardeningKitty,我们的猫友,会自动检查和评估Windows系统的硬化。

它还会检查像Microsoft Office和Microsoft Edge这样的单个应用程序。

PowerShell完美性:

运行HardeningKitty来评估您系统的安全姿态:

1
.\HardeningKitty.ps1 -AuditSystem

结论

通过使用PowerShell,我们施展了审计、保护和加固我们的Windows服务器。记住,安全是一个持续不断的追求 —— 让你的咒语锋利,让你的PowerShell脚本更加精湛!

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
function Collect-SystemLogs {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$CollectionID,

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

[Parameter()]
[ValidateSet("RealTime", "Scheduled", "OnDemand")]
[string]$CollectionMode = "RealTime",

[Parameter()]
[hashtable]$CollectionConfig,

[Parameter()]
[string]$LogPath
)

try {
$collector = [PSCustomObject]@{
CollectionID = $CollectionID
StartTime = Get-Date
CollectionStatus = @{}
Logs = @{}
Errors = @()
}

# 获取收集配置
$config = Get-CollectionConfig -CollectionID $CollectionID

# 管理收集
foreach ($type in $LogTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Logs = @{}
Errors = @()
}

# 应用收集配置
$typeConfig = Apply-CollectionConfig `
-Config $config `
-Type $type `
-Mode $CollectionMode `
-Settings $CollectionConfig

$status.Config = $typeConfig

# 收集系统日志
$logs = Gather-SystemLogs `
-Type $type `
-Config $typeConfig

$status.Logs = $logs
$collector.Logs[$type] = $logs

# 检查收集错误
$errors = Check-CollectionErrors `
-Logs $logs `
-Config $typeConfig

$status.Errors = $errors
$collector.Errors += $errors

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

$collector.CollectionStatus[$type] = $status
}

# 记录收集日志
if ($LogPath) {
$collector | ConvertTo-Json -Depth 10 | Out-File -FilePath $LogPath
}

# 更新收集器状态
$collector.EndTime = Get-Date

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

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

[Parameter()]
[ValidateSet("Pattern", "Anomaly", "Correlation")]
[string]$AnalysisMode = "Pattern",

[Parameter()]
[hashtable]$AnalysisConfig,

[Parameter()]
[string]$ReportPath
)

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

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

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

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

$status.Config = $typeConfig

# 分析日志模式
$patterns = Analyze-LogPatterns `
-Type $type `
-Config $typeConfig

$status.Patterns = $patterns
$analyzer.Patterns[$type] = $patterns

# 生成分析洞察
$insights = Generate-LogInsights `
-Patterns $patterns `
-Config $typeConfig

$status.Insights = $insights
$analyzer.Insights += $insights

# 更新分析状态
if ($insights.Count -gt 0) {
$status.Status = "InsightsFound"
}
else {
$status.Status = "NoInsights"
}

$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
}
}

日志归档

最后,创建一个用于管理日志归档的函数:

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 Archive-SystemLogs {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ArchiveID,

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

[Parameter()]
[ValidateSet("Compression", "Encryption", "Replication")]
[string]$ArchiveMode = "Compression",

[Parameter()]
[hashtable]$ArchiveConfig,

[Parameter()]
[string]$ReportPath
)

try {
$archiver = [PSCustomObject]@{
ArchiveID = $ArchiveID
StartTime = Get-Date
ArchiveStatus = @{}
Archives = @{}
Actions = @()
}

# 获取归档配置
$config = Get-ArchiveConfig -ArchiveID $ArchiveID

# 管理归档
foreach ($type in $ArchiveTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Archives = @{}
Actions = @()
}

# 应用归档配置
$typeConfig = Apply-ArchiveConfig `
-Config $config `
-Type $type `
-Mode $ArchiveMode `
-Settings $ArchiveConfig

$status.Config = $typeConfig

# 归档系统日志
$archives = Archive-LogFiles `
-Type $type `
-Config $typeConfig

$status.Archives = $archives
$archiver.Archives[$type] = $archives

# 执行归档动作
$actions = Execute-ArchiveActions `
-Archives $archives `
-Config $typeConfig

$status.Actions = $actions
$archiver.Actions += $actions

# 更新归档状态
if ($actions.Count -gt 0) {
$status.Status = "Archived"
}
else {
$status.Status = "Failed"
}

$archiver.ArchiveStatus[$type] = $status
}

# 生成报告
if ($ReportPath) {
$report = Generate-ArchiveReport `
-Archiver $archiver `
-Config $config

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

# 更新归档器状态
$archiver.EndTime = Get-Date

return $archiver
}
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
# 收集系统日志
$collector = Collect-SystemLogs -CollectionID "COLLECTION001" `
-LogTypes @("Application", "System", "Security", "Custom") `
-CollectionMode "RealTime" `
-CollectionConfig @{
"Application" = @{
"Source" = "Application"
"Level" = @("Error", "Warning", "Info")
"Filter" = "EventID > 0"
"Retention" = 7
}
"System" = @{
"Source" = "System"
"Level" = @("Error", "Warning", "Info")
"Filter" = "EventID > 0"
"Retention" = 7
}
"Security" = @{
"Source" = "Security"
"Level" = @("Success", "Failure")
"Filter" = "EventID > 0"
"Retention" = 30
}
"Custom" = @{
"Path" = "C:\Logs\Custom"
"Pattern" = "*.log"
"Filter" = "LastWriteTime > (Get-Date).AddDays(-1)"
"Retention" = 7
}
} `
-LogPath "C:\Logs\log_collection.json"

# 分析系统日志
$analyzer = Analyze-SystemLogs -AnalysisID "ANALYSIS001" `
-AnalysisTypes @("Error", "Performance", "Security") `
-AnalysisMode "Pattern" `
-AnalysisConfig @{
"Error" = @{
"Period" = "7d"
"Patterns" = @("Exception", "Timeout", "Connection")
"Threshold" = 10
"Report" = $true
}
"Performance" = @{
"Period" = "7d"
"Patterns" = @("Slow", "HighLoad", "Resource")
"Threshold" = 5
"Report" = $true
}
"Security" = @{
"Period" = "7d"
"Patterns" = @("Failed", "Unauthorized", "Suspicious")
"Threshold" = 3
"Report" = $true
}
} `
-ReportPath "C:\Reports\log_analysis.json"

# 归档系统日志
$archiver = Archive-SystemLogs -ArchiveID "ARCHIVE001" `
-ArchiveTypes @("Application", "System", "Security") `
-ArchiveMode "Compression" `
-ArchiveConfig @{
"Application" = @{
"Period" = "30d"
"Compression" = "GZip"
"Encryption" = "AES"
"Retention" = 365
}
"System" = @{
"Period" = "30d"
"Compression" = "GZip"
"Encryption" = "AES"
"Retention" = 365
}
"Security" = @{
"Period" = "30d"
"Compression" = "GZip"
"Encryption" = "AES"
"Retention" = 730
}
} `
-ReportPath "C:\Reports\log_archive.json"

最佳实践

  1. 实施日志收集
  2. 分析日志模式
  3. 管理日志归档
  4. 保持详细的日志记录
  5. 定期进行日志分析
  6. 实施归档策略
  7. 建立日志索引
  8. 保持系统文档更新

PowerShell 技能连载 - Azure Functions 集成

在无服务器计算时代,将PowerShell与Azure Functions集成可以为云服务带来强大的自动化能力。本文将介绍如何使用PowerShell构建一个Azure Functions管理系统,包括函数管理、触发器配置和监控分析等功能。

函数管理

首先,让我们创建一个用于管理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
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-AzureFunctions {
[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 "函数管理失败:$_"
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-FunctionTriggers {
[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 "触发器配置失败:$_"
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-FunctionPerformance {
[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-FunctionMetrics `
-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 "监控分析失败:$_"
return $null
}
}

使用示例

以下是如何使用这些函数来管理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
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
# 管理Azure Functions
$manager = Manage-AzureFunctions -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-FunctionTriggers -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-FunctionPerformance -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
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 Get-DeviceCompliance {
[CmdletBinding()]
param(
[ValidateSet('Basic','Advanced')]
[string]$CheckLevel = 'Basic'
)

$report = [PSCustomObject]@{
TPMEnabled = $false
BitLockerStatus = 'NotEncrypted'
FirewallActive = $false
LastUpdateDays = 999
Compliant = $false
}

try {
# TPM状态检查
$tpm = Get-CimInstance -ClassName Win32_Tpm -Namespace root/cimv2/Security/MicrosoftTpm
$report.TPMEnabled = $tpm.IsEnabled_InitialValue

# BitLocker检查
$blv = Get-BitLockerVolume -MountPoint $env:SystemDrive 2>$null
$report.BitLockerStatus = if($blv.ProtectionStatus -eq 'On') {'Encrypted'} else {'NotEncrypted'}

# 防火墙状态
$fw = Get-NetFirewallProfile | Where-Object {$_.Enabled -eq 'True'}
$report.FirewallActive = [bool]($fw | Measure-Object).Count

# 系统更新检查
$lastUpdate = (Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1).InstalledOn
$report.LastUpdateDays = (New-TimeSpan -Start $lastUpdate -End (Get-Date)).Days

# 高级检查
if($CheckLevel -eq 'Advanced') {
$report | Add-Member -NotePropertyName SecureBoot -NotePropertyValue (Confirm-SecureBootUEFI)
$report | Add-Member -NotePropertyName HyperVEnabled -NotePropertyValue (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State
}

# 合规判定
$report.Compliant = $report.TPMEnabled -and
($report.BitLockerStatus -eq 'Encrypted') -and
$report.FirewallActive -and
($report.LastUpdateDays -lt 30)
}
catch {
Write-Warning "设备检查异常: $_"
}

return $report
}

实现原理:

  1. 通过WMI/CIM接口获取TPM芯片状态,验证硬件安全基础
  2. 检查BitLocker加密状态,确保数据存储安全
  3. 扫描防火墙配置,确认至少有一个激活的防护配置文件
  4. 计算系统最后更新天数,确保漏洞及时修补
  5. 高级模式增加UEFI安全启动和虚拟化安全检查

使用示例:

1
2
3
4
5
# 基本检查
Get-DeviceCompliance

# 高级检查
Get-DeviceCompliance -CheckLevel Advanced

最佳实践:

  1. 与Intune等MDM解决方案集成
  2. 定期通过任务计划执行检查
  3. 对不合规设备启动修复流程
  4. 记录检查结果到中央日志服务器

注意事项:
• 需要本地管理员权限执行
• 部分检查仅支持Windows 10/11企业版
• 建议配合组策略共同使用

PowerShell 技能连载 - 25个最佳的Powershell脚本仓库

我最喜欢的部分之一是创建略有不同的脚本,我在这方面也取得了成功,并创建了Powershell脚本存储库。今天我必须说,我已经记不清自己创建了多少个脚本。除了ADDNSDHCP之外,此存储库还包含许多其他必备的脚本。从GPO到DFS Powershell脚本以及许多其他相关的Powershell脚本,使我的工作团队体验达到第九云。

这些脚本显然是为自动化而创建的,并且将它们保留在手头上被认为是犯罪行为,因此展示在该类别中。虽然我们知道组策略在任何环境中设置规则时起着重要作用,并且DFS也很重要,那么为什么不通过查看下面推荐书籍来更深入地了解它们呢?

为您提供的有用PowerShell命令

获取所有组策略命令

1
Get-command -Module grouppolicy

获取 GPO 报告

1
Get-GPOReport -All -Domain xyz.com

重置 GPO

1
Restore-GPO -Name "GPOname" -Path \\Server1\Backups

备份 GPO

1
Backup-Gpo -All -Path \\Server1\GpoBackups

获取DFS复制组

1
Get-DfsReplicationGroup -GroupName RG02

获取DFS复制成员

1
Get-DfsrMember -GroupName "RG07" -ComputerName "SRV01"

重启多台计算机

1
Restart-computer -computername A,B,C

获取所有服务

1
Get-service

我的Powershell脚本仓库

PowerShell 技能连载 - 使用 PowerShell 自动化 Windows 11 任务:实用指南

您想通过自动化Windows 11系统上的各种任务来节省时间和精力吗?如果是这样,您应该学习如何使用PowerShell,这是一种强大的脚本语言和命令行工具,可以帮助您更快速、更轻松地完成任务。在本博客中,我们将向您展示如何使用PowerShell来自动化Windows 11上常见或复杂任务的一些实际示例,例如:

  • 使用PowerShell管理网络设置和连接
  • 使用PowerShell监视系统性能和资源
  • 使用PowerShell备份和恢复文件夹与文件
  • 使用PowerShell安装和更新Windows功能
  • 使用PowerShell创建并运行定时任务

使用 PowerShell 管理网络设置与连接

PowerShell 可以帮助您轻松高效地管理 Windows 11 系统上的网络设置与连接。您可以使用 PowerShell 执行各种操作,比如配置 IP 地址、DNS 服务器、防火墙、代理以及 VPN。 您还可以使用 PowerShell 测试网络连通性、ping 命令、traceroute 和解析主机名。

1
2
3
4
5
6
7
8
9
10
11
# 定义接口别名, IP 地址, 子网掩码, 网关 和 DNS 服务器
$interface = "Ethernet"
$ip = "192.168.1.100"
$subnet = "255.255.255.0"
$gateway = "192.168.1.1"
$dns = "8.8.8.8"

# 设置接口的IP地址, DNS服务器 和 防火墙配置文件
Set-NetIPAddress -InterfaceAlias $interface -IPAddress $ip -PrefixLength $subnet -DefaultGateway $gateway
Set-DnsClientServerAddress -InterfaceAlias $interface -ServerAddresses $dns
Set-NetFirewallProfile -Profile Private -Enabled True

使用 PowerShell 监控系统性能和资源

PowerShell 可以帮助您轻松高效地监控 Windows 11 系统的系统性能和资源。您可以使用 PowerShell 执行各种操作,如获取 CPU、内存、磁盘和网络使用情况,测量命令或脚本的执行时间和内存消耗,并生成性能报告和图表。

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
# PowerShell script for monitoring system performance
# Define the performance counters for CPU and memory usage
$cpu = "\Processor(_Total)\% Processor Time"
$memory = "\Memory\Available MBytes"

# Get the performance counter data for CPU and memory usage
$data = Get-Counter -Counter $cpu,$memory -SampleInterval 1 -MaxSamples 10

# Create a chart object from the performance counter data
$chart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart
$chart.Width = 800
$chart.Height = 600
$chart.BackColor = "White"

# Add a chart area, a series for CPU usage, a series for memory usage, and a legend to the chart object
$area = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$area.AxisX.Title = "Time (seconds)"
$area.AxisY.Title = "Usage (%)"
$area.AxisY2.Title = "Available (MB)"
$chart.ChartAreas.Add($area)

$series1 = New-Object System.Windows.Forms.DataVisualization.Charting.Series
$series1.Name = "CPU"
$series1.ChartType = "Line"
$series1.Color = "Red"
$series1.BorderWidth = 3
$series1.Points.DataBindXY($data.Timestamps,$data.CounterSamples[0].CookedValue)
$chart.Series.Add($series1)

$series2 = New-Object System.Windows.Forms.DataVisualization.Charting.Series
$series2.Name = "Memory"
$series2.ChartType = "Line"
$series2.Color = "Blue"
$series2.BorderWidth = 3
$series2.YAxisType = "Secondary"
$series2.Points.DataBindXY($data.Timestamps,$data.CounterSamples[1].CookedValue)
$chart.Series.Add($series2)

$legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
$legend.Docking = "Top"
$chart.Legends.Add($legend)

# Save the chart object as an image file
$chart.SaveImage("C:\Performance.png","png")

使用 PowerShell 备份和恢复文件夹

PowerShell 可以帮助您轻松高效地备份和恢复 Windows 11 系统中的文件夹。您可以使用 PowerShell 执行各种操作,如创建、复制、移动、重命名、删除、搜索和压缩文件夹。您还可以使用 PowerShell 创建和使用备份策略、备份集和备份项。

1
2
3
4
5
6
7
8
9
10
11
12
13
# PowerShell script for backing up and restoring files and folders
# Define the folder to backup and the backup location
$folder = "C:\Users\YourName\Documents"
$location = "D:\Backup"

# Create a backup policy that runs daily and keeps backups for 30 days
$policy = New-BackupPolicy -Frequency Daily -RetentionPeriod 30

# Set the backup policy for the computer
Set-BackupPolicy -Policy $policy

# Backup the folder to the backup location
Backup-File -Source $folder -Destination $location

Here is a summary of a PowerShell script that restores a file or folder from a backup to a specified location:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Define the file or folder to restore and the restore location
$file = "C:\Users\YourName\Documents\Report.docx"
$location = "C:\Users\YourName\Desktop"

# Get the latest backup set that contains the file or folder
$set = Get-BackupSet | Sort-Object -Property CreationTime -Descending | Select-Object -First 1

# Get the backup item that matches the file or folder
$item = Get-BackupItem -BackupSet $set -Path $file

# Restore the file or folder to the restore location
Restore-File -BackupItem $item -Destination $location

使用 PowerShell 安装和更新 Windows 功能

PowerShell 可以帮助您轻松高效地在 Windows 11 系统上安装和更新 Windows 功能。您可以使用 PowerShell 执行各种操作,如列出、启用、禁用或更新诸如 Hyper-V、Windows 子系统 for Linux 或 Windows 沙盒等 Windows 功能。

1
2
3
# 用于安装和更新 Windows 功能的 PowerShell 脚本
# 在计算机上安装 Hyper-V 功能
Install-WindowsFeature -Name Hyper-V -IncludeManagementTools -Restart

以下是一个概要说明了一个 PowerShell 脚本,该脚本从计算机中卸载了 Windows 子系统 for Linux 功能并移除相关文件:

1
2
# 从计算机中卸载 Windows 子系统 for Linux 功能
Uninstall-WindowsFeature -Name Microsoft-Windows-Subsystem-Linux -Remove

使用 PowerShell 创建和运行定时任务

PowerShell 可以帮助您轻松高效地在 Windows 11 系统上创建和运行定时任务。您可以使用 PowerShell 执行各种操作,如创建、注册、启动、停止或禁用定时任务,例如运行一个 PowerShell 脚本、发送电子邮件或显示消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 用于创建和运行定时任务的 PowerShell 脚本
# 定义要运行的 PowerShell 脚本
$script = "C:\Scripts\Backup.ps1"

# 创建一个新的定时任务动作来运行这个 PowerShell 脚本
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File $script"

# 创建一个新的触发器,在每天早上10点执行该任务
$trigger = New-ScheduledTaskTrigger -Daily -At 10am

# 创建一组新的设置,如果任务执行时间过长则停止该任务
$setting = New-ScheduledTaskSettingSet -ExecutionTimeLimit (New-TimeSpan -Minutes 30)

# 在计算机上注册这个新的定时任务,并指定名称、动作、触发器及设置
Register-ScheduledTask –Name "Backup" –Action $action –Trigger $trigger –Setting $setting

结论

PowerShell 是一款多才多艺且强大的工具,可帮助您自动化处理在Windows 11系统上进行各种操作。您可以在官方PowerShell文档中找到更多关于PowerShell 的信息和示例。感谢阅读此篇博客文章。希望对你有所帮助并且有趣。 😊

PowerShell字符串操作实用指南

基础操作演示

1
2
3
4
5
6
7
8
# 字符串拼接优化
$result = -join ('Power','Shell','2024')

# 多行字符串处理
$text = @"
第一行内容
第二行内容
"@

常用处理方法

方法 描述 示例
Split() 分割字符串 ‘a,b,c’.Split(‘,’)
Replace() 替换字符 ‘123-456’.Replace(‘-‘,’’)
Substring() 截取子串 ‘abcdef’.Substring(2,3)

性能对比测试

1
2
3
# 拼接方式效率对比
Measure-Command { 1..10000 | %{ $str += $_ } } # 2.1s
Measure-Command { -join (1..10000) } # 0.03s

调试技巧

1
2
# 显示特殊字符
[System.BitConverter]::ToString([Text.Encoding]::UTF8.GetBytes($string))

最佳实践

  1. 优先使用-join运算符拼接大量字符串
  2. 避免在循环中进行字符串修改操作
  3. 使用StringBuilder处理动态内容

PowerShell 技能连载 - AI 集成技巧

在 PowerShell 中集成 AI 功能是一项前沿任务,本文将介绍一些实用的 AI 集成技巧。

首先,让我们看看如何与 OpenAI 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
# 创建 OpenAI 交互函数
function Invoke-OpenAIAPI {
param(
[string]$ApiKey,
[string]$Prompt,
[ValidateSet('gpt-4', 'gpt-3.5-turbo')]
[string]$Model = 'gpt-3.5-turbo',
[float]$Temperature = 0.7,
[int]$MaxTokens = 500
)

try {
$headers = @{
'Content-Type' = 'application/json'
'Authorization' = "Bearer $ApiKey"
}

$body = @{
model = $Model
messages = @(
@{
role = "user"
content = $Prompt
}
)
temperature = $Temperature
max_tokens = $MaxTokens
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri "https://api.openai.com/v1/chat/completions" -Method Post -Headers $headers -Body $body
return $response.choices[0].message.content
}
catch {
Write-Host "OpenAI API 调用失败:$_"
}
}

使用 AI 生成 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
# 创建 AI 脚本生成函数
function New-AIScript {
param(
[string]$ApiKey,
[string]$Description,
[string]$OutputPath
)

try {
$prompt = @"
生成一个 PowerShell 脚本,完成以下功能:$Description

要求:
1. 脚本应包含详细的注释
2. 包含适当的错误处理
3. 遵循 PowerShell 最佳实践
4. 只返回脚本代码,不要额外的解释
"@

$script = Invoke-OpenAIAPI -ApiKey $ApiKey -Prompt $prompt -MaxTokens 2000

if ($OutputPath) {
$script | Out-File -FilePath $OutputPath -Encoding UTF8
Write-Host "脚本已保存至:$OutputPath"
}

return $script
}
catch {
Write-Host "AI 脚本生成失败:$_"
}
}

利用 AI 进行日志分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 创建 AI 日志分析函数
function Analyze-LogsWithAI {
param(
[string]$ApiKey,
[string]$LogFilePath,
[string]$OutputPath,
[switch]$IncludeRecommendations
)

try {
$logs = Get-Content -Path $LogFilePath -Raw

# 将日志截断到合理的大小
if ($logs.Length -gt 4000) {
$logs = $logs.Substring(0, 4000) + "... [日志截断]"
}

$promptSuffix = ""
if ($IncludeRecommendations) {
$promptSuffix = "并提供解决方案建议。"
}

$prompt = @"
分析以下系统日志,识别可能的错误、警告和问题模式$promptSuffix

日志内容:
$logs
"@

$analysis = Invoke-OpenAIAPI -ApiKey $ApiKey -Prompt $prompt -MaxTokens 1500

if ($OutputPath) {
$analysis | Out-File -FilePath $OutputPath -Encoding UTF8
Write-Host "分析结果已保存至:$OutputPath"
}

return $analysis
}
catch {
Write-Host "AI 日志分析失败:$_"
}
}

AI 辅助的自动化故障排除:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 创建 AI 故障排除函数
function Start-AITroubleshooting {
param(
[string]$ApiKey,
[string]$Issue,
[switch]$RunDiagnostics
)

try {
$systemInfo = Get-ComputerInfo | ConvertTo-Json

if ($RunDiagnostics) {
$eventLogs = Get-WinEvent -LogName Application -MaxEvents 20 | Select-Object TimeCreated, LevelDisplayName, Message | ConvertTo-Json
$services = Get-Service | Where-Object { $_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic' } | ConvertTo-Json

$diagnosticInfo = @"
系统信息:
$systemInfo

最近事件日志:
$eventLogs

已停止的自动启动服务:
$services
"@
} else {
$diagnosticInfo = "系统信息:$systemInfo"
}

$prompt = @"
我有以下系统问题:$Issue

基于以下系统信息,提供排查步骤和可能的解决方案:

$diagnosticInfo
"@

$troubleshooting = Invoke-OpenAIAPI -ApiKey $ApiKey -Prompt $prompt -MaxTokens 2000 -Model 'gpt-4'

return $troubleshooting
}
catch {
Write-Host "AI 故障排除失败:$_"
}
}

使用 AI 优化 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
# 创建 AI 脚本优化函数
function Optimize-ScriptWithAI {
param(
[string]$ApiKey,
[string]$ScriptPath,
[string]$OutputPath,
[switch]$IncludeExplanation
)

try {
$script = Get-Content -Path $ScriptPath -Raw

$promptSuffix = ""
if ($IncludeExplanation) {
$promptSuffix = "并解释所做的改动和优化理由。"
}

$prompt = @"
优化以下 PowerShell 脚本的性能和代码质量$promptSuffix

脚本内容:
$script
"@

$optimizedScript = Invoke-OpenAIAPI -ApiKey $ApiKey -Prompt $prompt -MaxTokens 2000 -Model 'gpt-4'

if ($OutputPath) {
$optimizedScript | Out-File -FilePath $OutputPath -Encoding UTF8
Write-Host "优化后的脚本已保存至:$OutputPath"
}

return $optimizedScript
}
catch {
Write-Host "AI 脚本优化失败:$_"
}
}

这些技巧将帮助您更有效地在 PowerShell 中集成 AI 功能。记住,在处理 AI 相关任务时,始终要注意 API 密钥的安全性和成本控制。同时,建议使用适当的错误处理和日志记录机制来跟踪所有操作。

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

# 获取模块版本信息
$module = Get-InstalledModule -Name $ModuleName -ErrorAction Stop

# 调用漏洞数据库API
$response = Invoke-RestMethod -Uri "https://vulndb.example.com/api/modules/$($module.Name)/$($module.Version)"

# 生成安全报告
[PSCustomObject]@{
ModuleName = $module.Name
Version = $module.Version
Vulnerabilities = $response.vulns.Count
Critical = $response.vulns | Where-Object { $_.severity -eq 'Critical' } | Measure-Object | Select-Object -Expand Count
LastUpdated = $module.PublishedDate
} | Export-Csv -Path "$env:TEMP\ModuleSecurityScan_$(Get-Date -Format yyyyMMdd).csv" -Append
}

# 扫描常用模块
'PSReadLine', 'Pester', 'Az' | ForEach-Object {
Invoke-ModuleVulnerabilityScan -ModuleName $_ -Verbose
}

核心功能:

  1. 自动化检测已安装PowerShell模块版本
  2. 对接漏洞数据库API进行安全检查
  3. 生成包含严重性等级的安全报告

扩展方向:

  1. 集成软件物料清单(SBOM)生成
  2. 添加自动补丁更新功能
  3. 与CI/CD流水线集成实现预发布扫描

PowerShell循环结构深度解析

基础循环类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ForEach循环示例
$services = Get-Service
$services | ForEach-Object {
if ($_.Status -eq 'Running') {
Write-Host $_.DisplayName
}
}

# While循环应用场景
$counter = 0
while ($counter -lt 5) {
Start-Process notepad
$counter++
}

性能对比测试

循环类型 10万次迭代耗时 内存占用
ForEach-Object 1.2s 85MB
For循环 0.8s 45MB
While循环 0.7s 40MB

最佳实践建议

  1. 管道数据优先使用ForEach-Object
  2. 已知次数迭代使用For循环
  3. 条件控制迭代使用While循环
  4. 避免在循环体内执行重复计算

调试技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
# 设置循环断点
$i=0
1..10 | ForEach-Object {
$i++
if ($i -eq 5) { break }
$_
}

# 跟踪循环变量
Set-PSDebug -Trace 1
foreach ($file in (Get-ChildItem)) {
$file.Basename
}