Powershell ScriptBlock闭包:我是不是遗漏了什么



我已经为此挣扎了几个小时,在阅读了许多关于ScriptBlocks、Closures、scope等的线程后,我仍然没有发现我的代码中有什么问题。

让我解释一下:我有一个主脚本,它使用PSWriteHTML模块和ScriptBlocks动态生成HTML页面。

由于我有很多PSWriteHTML页面要写,我每次都使用ScriptBlock的arrayList来生成具有不同值集的代码(对应于不同的服务器),这些ScriptBlock被执行到foreach循环中。

这是使用保存利用率报告功能完成的(我只保留了相关代码):

function Save-utilizationReport ($currentDate, $navLinksScriptBlock, $htmlScriptBlockArray, $emeaTotalNumberOfCalls, $namTotalNumberOfCalls, $apacTotalNumberOfCalls, $path, $logFilePath) {

[...]
# Using Script Blocks, add the pages generated during the analysis to the HTML Report
foreach($htmlScriptBlock in $htmlScriptBlockArray){
Invoke-Command -ScriptBlock ($htmlScriptBlock)
}
[...]
}

ScriptBlock是使用从服务器日志列表中收集的一组值创建的,并添加到Create utilizationReportPage函数中的ScriptBlock数组列表中(同样,我只保留了相关代码):

function Create-utilizationReportPage ($matchedLines, $ipAddress, $hostname, $pageId, $utilisationReportTemplate, $htmlScriptBlockArray) {
# Retrieve the content of the Utilisation Report Template as a RAW string (Here-String)
$htmlPageCodeBlock = Get-Content $utilisationReportTemplate -Raw
# Create the Script Block that contains the HTML page
$htmlPageScriptBlock = {

# Get the "Total number of calls" information
$timeArray = $matchedLines.time
$participantNumberArray = $matchedLines.participantNumber
[...]

# Update the page ID in the template
$htmlPageCodeBlock = $htmlPageCodeBlock -replace '%PAGE_ID%', "$pageId"

# Update the page header information in the template
$htmlPageCodeBlock = $htmlPageCodeBlock -replace '%PAGE_HEADER%', "$ipAddress [$hostname]"

Invoke-Command -ScriptBlock ([scriptblock]::Create($htmlPageCodeBlock))
}.GetNewClosure()
# Add the Page's script block to the Script Blocks array
$htmlScriptBlockArray.Add($htmlPageScriptBlock)
}

这些在下面的脚本中被调用:

$currentDate = Get-CorrectDate $latestFolder
# The global Log file
$logFilePath = "$scriptPath/Logs/logs_$currentDate.txt"
$serversList = "$scriptPath/Config/$configFileName"
# If the Servers list exists, retrieve the Servers list
if (Test-Path $serversList) {
# Get the data from the file
[xml]$servers = Get-Content $serversList
# Select only the Servers information
$nodes = $servers.SelectNodes("//server")

try {

[...]

# Iterate through the Servers list
foreach ($node in $nodes) {

# Get the Server IP Address
$ipAddress = $node.ip

# Get the Server Hostname
$hostname = $node.hostname

# Get the "Debug Utilization" lines from the logbundle's syslog files
$matchedLines = [System.Collections.ArrayList]@(Find-UtilizationLinesInLogs $currentDate "$scriptPathData$currentDatelogs_$ipAddress" "host:server:  [USAGE] : {`"1`" : ")[-1]
# Add the Server's participants throughout the day
switch ($hostname) {
{$_.Contains("emea")} {
# Update EMEA total number of participants
Update-ZoneTotalParticipants ([ref]$emeaServer) ([ref]$emeaTotalNumberOfCalls) $matchedLines
}
{$_.Contains("nam")} {
# Update NAM total number of participants
Update-ZoneTotalParticipants ([ref]$namServer) ([ref]$namTotalNumberOfCalls) $matchedLines
}
{$_.Contains("apac")} {
# Update APAC total number of participants
Update-ZoneTotalParticipants ([ref]$apacServer) ([ref]$apacTotalNumberOfCalls) $matchedLines
}
}

# Get the CPU Utilization values lines from the logbundle's sysdebug files
$cpu = Get-CpuUsage "$scriptPathData$currentDatelogs_$ipAddresssysdebug"
# Get the Memory Utilization values lines from the logs' sysdebug files
$memory = Get-MemoryUsage "$scriptPathData$currentDatelogs_$ipAddresssysdebug"
# Export the "Debug Utilization" to a CSV file
Save-csvUtilizationReport $matchedLines "$scriptPathOutput$currentDate" "$ipAddress" "$hostname" $logFilePath
# Draw graphs from the "Debug Utilization" information and then export it to an HTML File
Create-utilizationReportPage $matchedLines "$ipAddress" "$hostname" $pageId $utilisationReportTemplate $htmlScriptBlockArray

# Add the new navigation link to the Navigation Links array
Add-htmlNavLink $navLinksArray "$ipAddress" "$hostname" $pageId $logFilePath

# Increment the Page ID counter
$pageId += 1
}

# Create an Here-String from the Navigation Links array
$OFS = ""
$navLinksCode =@"
$($navLinksArray)
"@
$OFS = " "
# Create a script block from the Navigation Links
$navLinksScriptBlock = [scriptblock]::Create($navLinksCode)
# Save the daily HTML utilization report
Save-utilizationReport $currentDate $navLinksScriptBlock $htmlScriptBlockArray $emeaTotalNumberOfCalls $namTotalNumberOfCalls $apacTotalNumberOfCalls "$scriptPathOutput$currentDate" $logFilePath
}
catch
{
Write-Logs $logFilePath "Error: $($_.Exception.Message)"

exit 1
}
}

除了第一页中的第一组值之外,一切都很好,而且都很好。。。

例如,当我有3个页面时,当执行Find UtilizationLinesInLoggs函数时,我可以看到收集的值是正确的:

  1. matchedLines.participantNumber:0 0 0 0了0 0 0,0 0 0 4 0 0 0 1 0 0 0 10 0 0 0、0 0 0和0 0 0

  2. matchedLines.participantNumber:"0 0 0 0"0 0">

  3. matchedLines.participantNumber:0 0 0 0了0 0 0,0 0 0 1 0 0 0 3 10 10 9 8 9 10 10 10 10 11 11 11 8 8 8 7 7 7 7 1 1 1 1 11 1 1 1 4 17 16

但是当在foreach循环中使用InvokeCommand执行ScriptBlocks时,第一批值系统地是3组值的总和,而以下值是正确的:

  1. matchedLines.participantCreate utilizationReportPage内的编号0 0 0 0 1 0 0 0 2 0 0 0 6 7 5 8 29 33 34 34 34 25 26 27 36 37 35 36 32 26 29 25 22 20 18 17 6 6 3 2 5 7 7 7 10 25 31 32 34

  2. 创建利用率报告页面内的matchedLines.participantNumber:"0 0 0 0"0 0">

  3. 创建利用率报告页面内的matchedLines.participantNumber:0 0 0 0了0 0 0,0 0 0 1 0 0 0 3 10 10 9 8 9 10 10 10 10 11 11 11 8 8 8 7 7 7 7 1 1 1 1 11 1 1 1 4 17 16

我尝试过很多事情都没有成功,所以如果有人有任何可能出错的迹象,那就太好了!

谢谢你的帮助!

所以!我终于发现了问题所在。

我怀疑我的问题与arrayList副本或至少与变量副本有关。。。因此,我试图删除脚本中提取$macthedLines值的这一部分,并使用引用将它们复制到全局数组中:

# Add the Server's participants throughout the day
switch ($hostname) {
{$_.Contains("emea")} {
# Update EMEA total number of participants
Update-ZoneTotalParticipants ([ref]$emeaServer) ([ref]$emeaTotalNumberOfCalls) $matchedLines
}
{$_.Contains("nam")} {
# Update NAM total number of participants
Update-ZoneTotalParticipants ([ref]$namServer) ([ref]$namTotalNumberOfCalls) $matchedLines
}
{$_.Contains("apac")} {
# Update APAC total number of participants
Update-ZoneTotalParticipants ([ref]$apacServer) ([ref]$apacTotalNumberOfCalls) $matchedLines
}
}

没错,这一次写在第一个PSWriteHTML页面中的值是正确的!

因此,我专注于更新ZoneTotal参与者功能,该功能正在复制值:

function Update-ZoneTotalParticipants ([ref][int]$ServerNumber, [ref][System.Collections.ArrayList]$totalNumberOfCalls, $values) {
# If this is the first server to be analysed in the zone
if ($ServerNumber.value -eq 1) {
# Copy the Utilization lines of the server
$totalNumberOfCalls.value = $values

# Increment the zone's server counter
$ServerNumber.value += 1
}
# If this at least the 2nd server to be analysed in the zone
elseif ($ServerNumber.value -gt 1) {
# Parse the server matched lines, get the participantNumber value and add it to the total
0..($totalNumberOfCalls.value.Count - 1) | ForEach-Object {
if ($_ -le ($values.Count - 1)) {
$totalNumberOfCalls.value[$_].participantNumber = [int]($totalNumberOfCalls.value[$_].participantNumber) + [int]($values[$_].participantNumber)
}
# If there are less objects in the current server matched lines, add a 0 instead
else {
$totalNumberOfCalls.value[$_].participantNumber = [int]($totalNumberOfCalls.value[$_].participantNumber) + 0
}
}
}
}

代码中唯一涉及$matchedLines的部分是$totalNumberOfCalls.value = $values,所以如果数组操作出错,肯定是这样。

因此,我查找了ArrayList副本或克隆,发现我没有对对象进行深入复制,这可能会导致问题。

我在这个线程中使用了Petru Zaharia的解决方案来更新函数:

# Copy the Utilization lines of the server
$totalNumberOfCalls.value = $values
# replaced with:
# Copy the Utilization lines of the server : Serialize and Deserialize data using PSSerializer:
$_TempCliXMLString = [System.Management.Automation.PSSerializer]::Serialize($matchedLines, [int32]::MaxValue)
$totalNumberOfCalls.value = [System.Management.Automation.PSSerializer]::Deserialize($_TempCliXMLString)

现在一切如预期。

感谢大家的支持!

相关内容

  • 没有找到相关文章

最新更新