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函数高级应用指南

函数参数校验

1
2
3
4
5
6
7
8
9
10
11
function Get-UserInfo {
param(
[Parameter(Mandatory)]
[ValidatePattern('^[a-zA-Z]+$')]
[string]$UserName,

[ValidateRange(18,120)]
[int]$Age
)
"用户: $UserName 年龄: $Age"
}

管道集成实战

1
2
3
4
5
6
7
8
9
10
11
12
function Process-Files {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline)]
[System.IO.FileInfo[]]$Files
)
process {
$_.FullName | ForEach-Object {
"处理文件: $_"
}
}
}

性能优化建议

  1. 避免在循环内创建函数
  2. 使用begin/process/end块处理流数据
  3. 合理使用参数集(ParameterSet)
  4. 采用类型约束提升执行效率

PowerShell错误处理核心机制

基础错误捕获结构

1
2
3
4
5
6
7
8
9
10
11
12
try {
Get-Content 'nonexistent.txt' -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
Write-Host "文件未找到: $($_.Exception.Message)"
}
catch {
Write-Host "未知错误: $($_.Exception.GetType().FullName)"
}
finally {
# 清理资源代码
}

错误变量解析

1
2
3
4
# 自动变量应用示例
$Error[0] | Format-List * -Force
$Error.Clear()
$ErrorActionPreference = 'Continue'

自定义错误抛出

1
2
3
4
5
6
function Validate-Range {
param([int]$Value)
if ($Value -notin 1..100) {
throw [System.ArgumentOutOfRangeException]::new('Value')
}
}

最佳实践

  1. 优先使用强类型异常捕获
  2. 合理设置ErrorActionPreference
  3. 保持finally块简洁
  4. 记录完整错误堆栈信息

PowerShell 技能连载 - CIM/WMI 管理技巧

在 PowerShell 中管理 CIM(Common Information Model)和 WMI(Windows Management Instrumentation)是一项重要任务,本文将介绍一些实用的 CIM/WMI 管理技巧。

首先,让我们看看基本的 CIM/WMI 操作:

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
# 创建 CIM/WMI 信息获取函数
function Get-CIMInfo {
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Namespace = "root/cimv2",
[string]$Class
)

try {
$session = New-CimSession -ComputerName $ComputerName
$instances = Get-CimInstance -CimSession $session -Namespace $Namespace -Class $Class

return [PSCustomObject]@{
ComputerName = $ComputerName
Namespace = $Namespace
Class = $Class
InstanceCount = $instances.Count
Properties = $instances[0].PSObject.Properties.Name
Instances = $instances
}
}
catch {
Write-Host "获取 CIM 信息失败:$_"
}
finally {
if ($session) {
Remove-CimSession -CimSession $session
}
}
}

CIM/WMI 查询优化:

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
# 创建 CIM/WMI 查询优化函数
function Optimize-CIMQuery {
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Namespace = "root/cimv2",
[string]$Class,
[hashtable]$Filter,
[string[]]$Properties,
[int]$Timeout = 30
)

try {
$session = New-CimSession -ComputerName $ComputerName -OperationTimeoutSec $Timeout

$query = "SELECT "
if ($Properties) {
$query += $Properties -join ","
}
else {
$query += "*"
}
$query += " FROM $Class"

if ($Filter) {
$query += " WHERE " + ($Filter.GetEnumerator() | ForEach-Object {
"$($_.Key) = '$($_.Value)'"
}) -join " AND "
}

$instances = Get-CimInstance -CimSession $session -Namespace $Namespace -Query $query

return [PSCustomObject]@{
Query = $query
InstanceCount = $instances.Count
ExecutionTime = $instances.PSIsContainer
Results = $instances
}
}
catch {
Write-Host "查询优化失败:$_"
}
finally {
if ($session) {
Remove-CimSession -CimSession $session
}
}
}

CIM/WMI 方法调用:

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
# 创建 CIM/WMI 方法调用函数
function Invoke-CIMMethod {
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Namespace = "root/cimv2",
[string]$Class,
[string]$Method,
[hashtable]$Parameters,
[hashtable]$Filter
)

try {
$session = New-CimSession -ComputerName $ComputerName

$instance = Get-CimInstance -CimSession $session -Namespace $Namespace -Class $Class -Filter ($Filter.GetEnumerator() | ForEach-Object {
"$($_.Key) = '$($_.Value)'"
}) -join " AND "

if ($instance) {
$result = Invoke-CimMethod -CimInstance $instance -MethodName $Method -Arguments $Parameters

return [PSCustomObject]@{
Success = $result.ReturnValue -eq 0
ReturnValue = $result.ReturnValue
ReturnDescription = $result.ReturnDescription
Parameters = $Parameters
}
}
else {
throw "未找到匹配的实例"
}
}
catch {
Write-Host "方法调用失败:$_"
}
finally {
if ($session) {
Remove-CimSession -CimSession $session
}
}
}

CIM/WMI 事件监控:

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
# 创建 CIM/WMI 事件监控函数
function Monitor-CIMEvents {
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Namespace = "root/cimv2",
[string]$Class,
[hashtable]$Filter,
[int]$Duration = 3600,
[scriptblock]$Action
)

try {
$session = New-CimSession -ComputerName $ComputerName
$query = "SELECT * FROM $Class"

if ($Filter) {
$query += " WHERE " + ($Filter.GetEnumerator() | ForEach-Object {
"$($_.Key) = '$($_.Value)'"
}) -join " AND "
}

$events = Register-CimIndicationEvent -CimSession $session -Namespace $Namespace -Query $query -Action $Action

Start-Sleep -Seconds $Duration

Unregister-Event -SourceIdentifier $events.Name
Remove-CimSession -CimSession $session

Write-Host "事件监控完成"
}
catch {
Write-Host "事件监控失败:$_"
}
finally {
if ($session) {
Remove-CimSession -CimSession $session
}
}
}

CIM/WMI 性能优化:

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
# 创建 CIM/WMI 性能优化函数
function Optimize-CIMPerformance {
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Namespace = "root/cimv2",
[string]$Class,
[int]$BatchSize = 100,
[int]$MaxThreads = 4
)

try {
$session = New-CimSession -ComputerName $ComputerName
$instances = Get-CimInstance -CimSession $session -Namespace $Namespace -Class $Class

$batches = @()
for ($i = 0; $i -lt $instances.Count; $i += $BatchSize) {
$batches += $instances[$i..([math]::Min($i + $BatchSize - 1, $instances.Count - 1))]
}

$results = @()
$batches | ForEach-Object -ThrottleLimit $MaxThreads -Parallel {
$batch = $_
$session = New-CimSession -ComputerName $using:ComputerName

$batch | ForEach-Object {
# 在这里添加批处理逻辑
[PSCustomObject]@{
Instance = $_.Name
Status = "Processed"
}
}

Remove-CimSession -CimSession $session
}

return [PSCustomObject]@{
TotalInstances = $instances.Count
BatchCount = $batches.Count
Results = $results
}
}
catch {
Write-Host "性能优化失败:$_"
}
finally {
if ($session) {
Remove-CimSession -CimSession $session
}
}
}

这些技巧将帮助您更有效地管理 CIM/WMI。记住,在处理 CIM/WMI 时,始终要注意查询性能和资源使用。同时,建议使用适当的错误处理和会话管理机制来确保操作的可靠性。

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
function Check-DeviceHealth {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$DeviceID,

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

[Parameter()]
[hashtable]$Thresholds,

[Parameter()]
[string]$ReportPath,

[Parameter()]
[switch]$AutoRemediate
)

try {
$checker = [PSCustomObject]@{
DeviceID = $DeviceID
StartTime = Get-Date
HealthStatus = @{}
Issues = @()
Remediations = @()
}

# 获取设备信息
$device = Get-DeviceInfo -DeviceID $DeviceID

# 执行健康检查
foreach ($type in $CheckTypes) {
$check = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Score = 0
Details = @{}
Issues = @()
}

# 检查系统状态
$systemStatus = Get-SystemStatus `
-Device $device `
-Type $type

$check.Details = $systemStatus

# 评估健康状态
$healthScore = Calculate-HealthScore `
-Status $systemStatus `
-Thresholds $Thresholds

$check.Score = $healthScore

# 检查问题
$issues = Find-HealthIssues `
-Status $systemStatus `
-Score $healthScore

if ($issues.Count -gt 0) {
$check.Issues = $issues
$check.Status = "Unhealthy"
$checker.Issues += $issues

# 自动修复
if ($AutoRemediate) {
$remediations = Start-HealthRemediation `
-Device $device `
-Issues $issues

$checker.Remediations += $remediations
}
}
else {
$check.Status = "Healthy"
}

$checker.HealthStatus[$type] = $check
}

# 生成报告
if ($ReportPath) {
$report = Generate-HealthReport `
-Checker $checker `
-Device $device

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

# 更新检查器状态
$checker.EndTime = Get-Date

return $checker
}
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
function Manage-AccessControl {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ResourceID,

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

[Parameter()]
[ValidateSet("Strict", "Standard", "Basic")]
[string]$SecurityLevel = "Standard",

[Parameter()]
[hashtable]$Policies,

[Parameter()]
[string]$LogPath
)

try {
$manager = [PSCustomObject]@{
ResourceID = $ResourceID
StartTime = Get-Date
AccessControls = @{}
Sessions = @()
Violations = @()
}

# 获取资源信息
$resource = Get-ResourceInfo -ResourceID $ResourceID

# 配置访问控制
foreach ($type in $AccessTypes) {
$control = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Policies = @{}
AccessList = @()
Restrictions = @{}
}

# 应用访问策略
$policy = Apply-AccessPolicy `
-Resource $resource `
-Type $type `
-Level $SecurityLevel `
-Policies $Policies

$control.Policies = $policy

# 配置访问限制
$restrictions = Set-AccessRestrictions `
-Policy $policy `
-Resource $resource

$control.Restrictions = $restrictions

# 更新访问列表
$accessList = Update-AccessList `
-Resource $resource `
-Policy $policy

$control.AccessList = $accessList

# 检查访问违规
$violations = Check-AccessViolations `
-AccessList $accessList `
-Policy $policy

if ($violations.Count -gt 0) {
$control.Status = "Violation"
$manager.Violations += $violations
}
else {
$control.Status = "Compliant"
}

$manager.AccessControls[$type] = $control
}

# 管理访问会话
$sessions = Manage-AccessSessions `
-Resource $resource `
-Controls $manager.AccessControls

$manager.Sessions = $sessions

# 记录访问日志
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
function Manage-AccessSessions {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$SessionID,

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

[Parameter()]
[ValidateSet("Active", "Inactive", "Terminated")]
[string]$Status = "Active",

[Parameter()]
[hashtable]$SessionConfig,

[Parameter()]
[string]$LogPath
)

try {
$sessionManager = [PSCustomObject]@{
SessionID = $SessionID
StartTime = Get-Date
Sessions = @{}
Activities = @()
SecurityEvents = @()
}

# 获取会话信息
$session = Get-SessionInfo -SessionID $SessionID

# 管理会话
foreach ($type in $SessionTypes) {
$sessionInfo = [PSCustomObject]@{
Type = $type
Status = $Status
Config = @{}
Activities = @()
Security = @{}
}

# 应用会话配置
$config = Apply-SessionConfig `
-Session $session `
-Type $type `
-Config $SessionConfig

$sessionInfo.Config = $config

# 监控会话活动
$activities = Monitor-SessionActivities `
-Session $session `
-Type $type

$sessionInfo.Activities = $activities
$sessionManager.Activities += $activities

# 检查安全事件
$securityEvents = Check-SecurityEvents `
-Session $session `
-Activities $activities

$sessionInfo.Security = $securityEvents
$sessionManager.SecurityEvents += $securityEvents

# 更新会话状态
$sessionInfo.Status = Update-SessionStatus `
-Session $session `
-Events $securityEvents

$sessionManager.Sessions[$type] = $sessionInfo
}

# 记录会话日志
if ($LogPath) {
$sessionManager | ConvertTo-Json -Depth 10 | Out-File -FilePath $LogPath
}

# 更新会话管理器状态
$sessionManager.EndTime = Get-Date

return $sessionManager
}
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
# 检查设备健康状态
$checker = Check-DeviceHealth -DeviceID "DEV001" `
-CheckTypes @("System", "Security", "Compliance") `
-Thresholds @{
"System" = @{
"CPUUsage" = 80
"MemoryUsage" = 85
"DiskSpace" = 90
}
"Security" = @{
"AntivirusStatus" = "Enabled"
"FirewallStatus" = "Enabled"
"UpdatesStatus" = "UpToDate"
}
"Compliance" = @{
"PolicyCompliance" = 95
"SecurityScore" = 85
}
} `
-ReportPath "C:\Reports\device_health.json" `
-AutoRemediate

# 管理访问控制
$manager = Manage-AccessControl -ResourceID "RES001" `
-AccessTypes @("Network", "Application", "Data") `
-SecurityLevel "Strict" `
-Policies @{
"Network" = @{
"AllowedIPs" = @("192.168.1.0/24")
"Ports" = @(80, 443, 3389)
"Protocols" = @("TCP", "UDP")
}
"Application" = @{
"AllowedApps" = @("Chrome", "Office")
"BlockedApps" = @("Tor", "P2P")
"Permissions" = @("Read", "Write")
}
"Data" = @{
"Encryption" = "Required"
"AccessLevel" = "Restricted"
"AuditLog" = "Enabled"
}
} `
-LogPath "C:\Logs\access_control.json"

# 管理访问会话
$sessionManager = Manage-AccessSessions -SessionID "SESS001" `
-SessionTypes @("User", "Service", "System") `
-Status "Active" `
-SessionConfig @{
"User" = @{
"MaxDuration" = 480
"IdleTimeout" = 30
"MFARequired" = $true
}
"Service" = @{
"MaxDuration" = 1440
"IdleTimeout" = 60
"MFARequired" = $false
}
"System" = @{
"MaxDuration" = 0
"IdleTimeout" = 0
"MFARequired" = $false
}
} `
-LogPath "C:\Logs\session_management.json"

最佳实践

  1. 实施设备健康检查
  2. 管理访问控制
  3. 监控会话活动
  4. 保持详细的运行记录
  5. 定期进行安全评估
  6. 实施安全策略
  7. 建立应急响应机制
  8. 保持系统文档更新

PowerShell变量作用域深度解析

基础作用域类型

1
2
3
4
5
6
7
$global:counter = 10  # 全局作用域

function Show-Count {
$script:total = 20 # 脚本作用域
$local:temp = 5 # 局部作用域
$global:counter + $script:total + $local:temp
}

作用域穿透技巧

1
2
3
4
5
6
7
# 使用Get-Variable跨作用域访问
Get-Variable counter -Scope Global

# 使用Set-Variable修改父作用域
function Update-Count {
Set-Variable -Name counter -Value 15 -Scope 1
}

最佳实践

  1. 优先使用参数传递替代跨作用域访问
  2. 谨慎使用global作用域
  3. 在模块中使用$script作用域保持状态
  4. 使用private修饰符保护关键变量

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 Manage-ProductionLine {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$LineID,

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

[Parameter()]
[ValidateSet("Monitor", "Control", "Optimize")]
[string]$OperationMode = "Monitor",

[Parameter()]
[hashtable]$LineConfig,

[Parameter()]
[string]$LogPath
)

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

# 获取生产线配置
$config = Get-LineConfig -LineID $LineID

# 管理生产线
foreach ($type in $LineTypes) {
$status = [PSCustomObject]@{
Type = $type
Status = "Unknown"
Config = @{}
Operations = @{}
Issues = @()
}

# 应用生产线配置
$typeConfig = Apply-LineConfig `
-Config $config `
-Type $type `
-Mode $OperationMode `
-Settings $LineConfig

$status.Config = $typeConfig

# 执行生产线操作
$operations = Execute-LineOperations `
-Type $type `
-Config $typeConfig

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

# 检查生产线问题
$issues = Check-LineIssues `
-Operations $operations `
-Config $typeConfig

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

# 更新生产线状态
if ($issues.Count -gt 0) {
$status.Status = "Warning"
}
else {
$status.Status = "Normal"
}

$manager.LineStatus[$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 Monitor-ManufacturingDevices {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$MonitorID,

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

[Parameter()]
[ValidateSet("Status", "Performance", "Maintenance")]
[string]$MonitorMode = "Status",

[Parameter()]
[hashtable]$MonitorConfig,

[Parameter()]
[string]$ReportPath
)

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

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

# 监控设备
foreach ($type in $DeviceTypes) {
$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-DeviceMetrics `
-Type $type `
-Config $typeConfig

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

# 检查设备告警
$alerts = Check-DeviceAlerts `
-Metrics $metrics `
-Config $typeConfig

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

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

$monitor.DeviceStatus[$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
}
}

库存控制

最后,创建一个用于控制库存的函数:

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 Manage-Inventory {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$InventoryID,

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

[Parameter()]
[ValidateSet("Track", "Optimize", "Report")]
[string]$OperationMode = "Track",

[Parameter()]
[hashtable]$InventoryConfig,

[Parameter()]
[string]$ReportPath
)

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

# 获取库存配置
$config = Get-InventoryConfig -InventoryID $InventoryID

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

# 应用库存配置
$typeConfig = Apply-InventoryConfig `
-Config $config `
-Type $type `
-Mode $OperationMode `
-Settings $InventoryConfig

$status.Config = $typeConfig

# 执行库存操作
$operations = Execute-InventoryOperations `
-Type $type `
-Config $typeConfig

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

# 检查库存问题
$issues = Check-InventoryIssues `
-Operations $operations `
-Config $typeConfig

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

# 更新库存状态
if ($issues.Count -gt 0) {
$status.Status = "Warning"
}
else {
$status.Status = "Normal"
}

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

# 生成报告
if ($ReportPath) {
$report = Generate-InventoryReport `
-Manager $manager `
-Config $config

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

# 更新管理器状态
$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
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# 管理生产线
$manager = Manage-ProductionLine -LineID "LINE001" `
-LineTypes @("Assembly", "Packaging", "Quality") `
-OperationMode "Monitor" `
-LineConfig @{
"Assembly" = @{
"Stations" = @{
"Station1" = @{
"Metrics" = @("Efficiency", "Quality", "Downtime")
"Threshold" = 95
"Interval" = 60
}
"Station2" = @{
"Metrics" = @("Efficiency", "Quality", "Downtime")
"Threshold" = 95
"Interval" = 60
}
}
"Controls" = @{
"Speed" = $true
"Temperature" = $true
"Pressure" = $true
}
}
"Packaging" = @{
"Stations" = @{
"Station1" = @{
"Metrics" = @("Speed", "Accuracy", "Waste")
"Threshold" = 90
"Interval" = 30
}
"Station2" = @{
"Metrics" = @("Speed", "Accuracy", "Waste")
"Threshold" = 90
"Interval" = 30
}
}
"Controls" = @{
"Weight" = $true
"Sealing" = $true
"Labeling" = $true
}
}
"Quality" = @{
"Stations" = @{
"Station1" = @{
"Metrics" = @("Defects", "Accuracy", "Calibration")
"Threshold" = 99
"Interval" = 120
}
"Station2" = @{
"Metrics" = @("Defects", "Accuracy", "Calibration")
"Threshold" = 99
"Interval" = 120
}
}
"Controls" = @{
"Inspection" = $true
"Testing" = $true
"Documentation" = $true
}
}
} `
-LogPath "C:\Logs\production_line.json"

# 监控制造设备
$monitor = Monitor-ManufacturingDevices -MonitorID "MONITOR001" `
-DeviceTypes @("Robots", "CNC", "Conveyors") `
-MonitorMode "Status" `
-MonitorConfig @{
"Robots" = @{
"Devices" = @{
"Robot1" = @{
"Metrics" = @("Position", "Speed", "Torque")
"Threshold" = 95
"Interval" = 30
}
"Robot2" = @{
"Metrics" = @("Position", "Speed", "Torque")
"Threshold" = 95
"Interval" = 30
}
}
"Alerts" = @{
"Critical" = $true
"Warning" = $true
"Notification" = "Email"
}
}
"CNC" = @{
"Devices" = @{
"CNC1" = @{
"Metrics" = @("Accuracy", "Speed", "ToolLife")
"Threshold" = 95
"Interval" = 60
}
"CNC2" = @{
"Metrics" = @("Accuracy", "Speed", "ToolLife")
"Threshold" = 95
"Interval" = 60
}
}
"Alerts" = @{
"Critical" = $true
"Warning" = $true
"Notification" = "SMS"
}
}
"Conveyors" = @{
"Devices" = @{
"Conveyor1" = @{
"Metrics" = @("Speed", "Load", "Alignment")
"Threshold" = 90
"Interval" = 30
}
"Conveyor2" = @{
"Metrics" = @("Speed", "Load", "Alignment")
"Threshold" = 90
"Interval" = 30
}
}
"Alerts" = @{
"Critical" = $true
"Warning" = $true
"Notification" = "Email"
}
}
} `
-ReportPath "C:\Reports\device_monitoring.json"

# 管理库存
$manager = Manage-Inventory -InventoryID "INV001" `
-InventoryTypes @("Raw", "WorkInProgress", "Finished") `
-OperationMode "Track" `
-InventoryConfig @{
"Raw" = @{
"Items" = @{
"Material1" = @{
"Thresholds" = @{
"Min" = 1000
"Max" = 5000
}
"Tracking" = @{
"Location" = $true
"Lot" = $true
"Expiry" = $true
}
}
"Material2" = @{
"Thresholds" = @{
"Min" = 500
"Max" = 2000
}
"Tracking" = @{
"Location" = $true
"Lot" = $true
"Expiry" = $true
}
}
}
"Controls" = @{
"Reorder" = $true
"Quality" = $true
"Storage" = $true
}
}
"WorkInProgress" = @{
"Items" = @{
"Product1" = @{
"Thresholds" = @{
"Min" = 100
"Max" = 500
}
"Tracking" = @{
"Stage" = $true
"Time" = $true
"Quality" = $true
}
}
"Product2" = @{
"Thresholds" = @{
"Min" = 50
"Max" = 200
}
"Tracking" = @{
"Stage" = $true
"Time" = $true
"Quality" = $true
}
}
}
"Controls" = @{
"Flow" = $true
"Quality" = $true
"Efficiency" = $true
}
}
"Finished" = @{
"Items" = @{
"Product1" = @{
"Thresholds" = @{
"Min" = 200
"Max" = 1000
}
"Tracking" = @{
"Location" = $true
"Lot" = $true
"Quality" = $true
}
}
"Product2" = @{
"Thresholds" = @{
"Min" = 100
"Max" = 500
}
"Tracking" = @{
"Location" = $true
"Lot" = $true
"Quality" = $true
}
}
}
"Controls" = @{
"Storage" = $true
"Quality" = $true
"Distribution" = $true
}
}
} `
-ReportPath "C:\Reports\inventory_management.json"

最佳实践

  1. 实施生产线管理
  2. 监控制造设备
  3. 控制库存水平
  4. 保持详细的生产记录
  5. 定期进行设备维护
  6. 实施质量控制
  7. 建立应急响应机制
  8. 保持系统文档更新

PowerShell 技能连载 - Docker容器生命周期管理

在容器化技术广泛应用的今天,Docker容器的日常管理成为运维工作的重要环节。本文将演示如何通过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
function Manage-DockerContainer {
param(
[ValidateSet('Create','Start','Stop','Remove')]
[string]$Action,
[string]$ImageName,
[string]$ContainerName
)

try {
switch ($Action) {
'Create' {
docker run -d --name $ContainerName $ImageName
}
'Start' {
docker start $ContainerName
}
'Stop' {
docker stop $ContainerName
}
'Remove' {
docker rm -f $ContainerName
}
}

# 获取容器状态
$status = docker inspect -f '{{.State.Status}}' $ContainerName
Write-Host "$($Action)操作完成,当前状态:$status"
}
catch {
Write-Error "$Action操作失败:$_"
}
}

实现原理分析:

  1. 通过Docker命令行接口实现容器操作
  2. 参数验证机制确保操作类型合法性
  3. 支持创建/启动/停止/删除四大核心操作
  4. 操作完成后自动获取并返回容器实时状态
  5. 异常处理机制捕获常见容器操作错误

该脚本将容器管理操作封装为可重复使用的函数,特别适合需要批量管理多个容器实例的微服务架构场景。

PowerShell正则表达式入门精要

基础匹配模式

1
2
3
4
5
6
7
8
# 邮箱验证正则
$emailPattern = '^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'
'test@example.com' -match $emailPattern # 返回True

# 提取电话号码
$text = '联系电话:010-12345678 或 13800138000'
$text -match '\d{3,4}-\d{7,8}'
$matches[0] # 输出010-12345678

正则表达式元字符

字符 功能描述 示例
. 匹配任意字符 a.c → abc
\d 匹配数字 \d{3} → 123
\w 匹配字母数字下划线 \w+ → abc123
^ 匹配行首 ^Start
$ 匹配行尾 end$

替换操作示例

1
2
3
4
5
6
7
# 日期格式转换
'2024-04-07' -replace '(\d{4})-(\d{2})-(\d{2})','$3/$2/$1'
# 输出07/04/2024

# 清理多余空格
'PowerShell 正则 教程' -replace '\s+',' '
# 输出PowerShell 正则 教程

性能优化建议

  1. 预编译常用正则表达式
  2. 避免贪婪匹配引发性能问题
  3. 使用非捕获组(?:)减少内存开销

PowerShell 技能连载 - PDF 处理技巧

在 PowerShell 中处理 PDF 文件是一项常见任务,本文将介绍一些实用的 PDF 处理技巧。

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

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
# 创建 PDF 信息获取函数
function Get-PDFInfo {
param(
[string]$PDFPath
)

try {
# 使用 iTextSharp 获取 PDF 信息
Add-Type -Path "itextsharp.dll"
$reader = [iTextSharp.text.pdf.PdfReader]::new($PDFPath)

$info = [PSCustomObject]@{
FileName = Split-Path $PDFPath -Leaf
PageCount = $reader.NumberOfPages
FileSize = (Get-Item $PDFPath).Length
IsEncrypted = $reader.IsEncrypted()
Metadata = $reader.Info
}

$reader.Close()
return $info
}
catch {
Write-Host "获取 PDF 信息失败:$_"
}
}

PDF 合并:

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
# 创建 PDF 合并函数
function Merge-PDFFiles {
param(
[string[]]$InputFiles,
[string]$OutputPath
)

try {
Add-Type -Path "itextsharp.dll"
$document = [iTextSharp.text.Document]::new()
$writer = [iTextSharp.text.pdf.PdfCopy]::new($document, [System.IO.FileStream]::new($OutputPath, [System.IO.FileMode]::Create))

$document.Open()

foreach ($file in $InputFiles) {
$reader = [iTextSharp.text.pdf.PdfReader]::new($file)
for ($i = 1; $i -le $reader.NumberOfPages; $i++) {
$writer.AddPage($writer.GetImportedPage($reader, $i))
}
$reader.Close()
}

$document.Close()
$writer.Close()

Write-Host "PDF 合并完成:$OutputPath"
}
catch {
Write-Host "合并失败:$_"
}
}

PDF 分割:

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
# 创建 PDF 分割函数
function Split-PDF {
param(
[string]$InputPath,
[string]$OutputFolder,
[int[]]$PageRanges
)

try {
Add-Type -Path "itextsharp.dll"
$reader = [iTextSharp.text.pdf.PdfReader]::new($InputPath)

for ($i = 0; $i -lt $PageRanges.Count; $i += 2) {
$startPage = $PageRanges[$i]
$endPage = if ($i + 1 -lt $PageRanges.Count) { $PageRanges[$i + 1] } else { $reader.NumberOfPages }

$outputPath = Join-Path $OutputFolder "split_$($startPage)_$($endPage).pdf"
$document = [iTextSharp.text.Document]::new()
$writer = [iTextSharp.text.pdf.PdfCopy]::new($document, [System.IO.FileStream]::new($outputPath, [System.IO.FileMode]::Create))

$document.Open()

for ($page = $startPage; $page -le $endPage; $page++) {
$writer.AddPage($writer.GetImportedPage($reader, $page))
}

$document.Close()
$writer.Close()
}

$reader.Close()
Write-Host "PDF 分割完成"
}
catch {
Write-Host "分割失败:$_"
}
}

PDF 加密:

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
# 创建 PDF 加密函数
function Protect-PDF {
param(
[string]$InputPath,
[string]$OutputPath,
[string]$UserPassword,
[string]$OwnerPassword
)

try {
Add-Type -Path "itextsharp.dll"
$reader = [iTextSharp.text.pdf.PdfReader]::new($InputPath)
$stamper = [iTextSharp.text.pdf.PdfStamper]::new($reader, [System.IO.FileStream]::new($OutputPath, [System.IO.FileMode]::Create))

# 设置加密
$stamper.SetEncryption(
[System.Text.Encoding]::UTF8.GetBytes($UserPassword),
[System.Text.Encoding]::UTF8.GetBytes($OwnerPassword),
[iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING -bor
[iTextSharp.text.pdf.PdfWriter]::ALLOW_COPY -bor
[iTextSharp.text.pdf.PdfWriter]::ALLOW_FILL_IN -bor
[iTextSharp.text.pdf.PdfWriter]::ALLOW_SCREENREADERS,
[iTextSharp.text.pdf.PdfWriter]::ENCRYPTION_AES_128
)

$stamper.Close()
$reader.Close()

Write-Host "PDF 加密完成:$OutputPath"
}
catch {
Write-Host "加密失败:$_"
}
}

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