@kevlns/xlmerge 2.0.5 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,140 +1,140 @@
1
- [CmdletBinding()]
2
- param([string]$ParametersPath, [string]$CleanupParametersPath)
3
-
4
- $ErrorActionPreference = 'Stop'
5
- $excel = $null
6
- $book = $null
7
- $excelPid = $null
8
- $ownedExcel = $false
9
- $excelStartFileTimeUtc = $null
10
- $statePath = $null
11
-
12
- if (![string]::IsNullOrWhiteSpace($CleanupParametersPath)) {
13
- try {
14
- $owned = Get-Content -LiteralPath $CleanupParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
15
- $p = Get-Process -Id ([int]$owned.pid) -ErrorAction SilentlyContinue
16
- if ($p -and $p.ProcessName -ieq 'EXCEL') {
17
- $ft = $p.StartTime.ToUniversalTime().ToFileTimeUtc()
18
- if ($ft -eq [int64]$owned.startFileTimeUtc) {
19
- Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
20
- }
21
- }
22
- exit 0
23
- } catch { exit 1 }
24
- }
25
- if ([string]::IsNullOrWhiteSpace($ParametersPath)) { throw 'ParametersPath is required' }
26
-
27
- if (-not ('XlmergeExcelWindow' -as [type])) {
28
- Add-Type @"
29
- using System;
30
- using System.Runtime.InteropServices;
31
- public static class XlmergeExcelWindow {
32
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
33
- }
34
- "@
35
- }
36
-
37
- function Write-State([string]$status, [string]$errorText = $null) {
38
- if ([string]::IsNullOrWhiteSpace($statePath)) { return }
39
- $state = [ordered]@{ status = $status }
40
- if ($null -ne $excelPid) {
41
- $state.pid = [int]$excelPid
42
- if ($null -ne $excelStartFileTimeUtc) { $state.startFileTimeUtc = [int64]$excelStartFileTimeUtc }
43
- }
44
- if ($null -ne $errorText) { $state.error = $errorText }
45
- $state | ConvertTo-Json -Compress | Set-Content -LiteralPath $statePath -Encoding UTF8
46
- }
47
-
48
- try {
49
- $parameters = Get-Content -LiteralPath $ParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
50
- $source = [IO.Path]::GetFullPath([string]$parameters.source)
51
- $result = [IO.Path]::GetFullPath([string]$parameters.result)
52
- $statePath = [IO.Path]::GetFullPath([string]$parameters.state)
53
- $timeoutSeconds = [int]$parameters.timeoutSeconds
54
- if ($timeoutSeconds -lt 1) { throw 'timeoutSeconds must be positive' }
55
- if (!(Test-Path -LiteralPath $source -PathType Leaf)) { throw "Source workbook does not exist: $source" }
56
- $parent = Split-Path -Parent $result
57
- if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
58
-
59
- # Excel constants are used as numbers so this script has no interop assembly
60
- # dependency. AutomationSecurity=3 is msoAutomationSecurityForceDisable.
61
- $existingExcelPids = @(Get-Process -Name EXCEL -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
62
- $excel = New-Object -ComObject Excel.Application
63
- $window = [IntPtr]$excel.Hwnd
64
- [uint32]$windowPid = 0
65
- [XlmergeExcelWindow]::GetWindowThreadProcessId($window, [ref]$windowPid) | Out-Null
66
- if ($windowPid -eq 0) { throw 'Unable to identify the Excel process created for this calculation' }
67
- $excelProcess = Get-Process -Id ([int]$windowPid) -ErrorAction Stop
68
- if ($excelProcess.ProcessName -ine 'EXCEL') { throw 'Excel window belongs to an unexpected process' }
69
- if ($existingExcelPids -contains $excelProcess.Id) { throw 'Excel COM attached to a pre-existing user Excel process' }
70
- $excelPid = $excelProcess.Id
71
- $excelStartFileTimeUtc = [int64]$excelProcess.StartTime.ToUniversalTime().ToFileTimeUtc()
72
- $ownedExcel = $true
73
- Write-State 'running'
74
-
75
- $excel.Visible = $false
76
- $excel.DisplayAlerts = $false
77
- $excel.EnableEvents = $false
78
- $excel.ScreenUpdating = $false
79
- $excel.AskToUpdateLinks = $false
80
- $excel.AutomationSecurity = 3
81
- $excel.UserControl = $false
82
- # UpdateLinks=0 and ReadOnly=true are positional arguments in the Excel COM
83
- # API. The temporary source is never saved in place.
84
- $book = $excel.Workbooks.Open($source, 0, $true)
85
- # Iterative calculation can make a circular workbook appear to have a
86
- # stable value. Check after opening the workbook: with no open workbooks,
87
- # some Excel versions report Application.Iteration as true unconditionally.
88
- if ($excel.Iteration) { throw 'Workbook enables iterative calculation' }
89
- $excel.CalculateFullRebuild()
90
- $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
91
- while ($excel.CalculationState -ne 0) { # xlDone
92
- if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation did not reach xlDone before timeout' }
93
- Start-Sleep -Milliseconds 100
94
- }
95
- if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation exceeded timeout' }
96
- try {
97
- $circular = $excel.CircularReference
98
- if ($null -ne $circular) { throw 'Workbook contains a circular reference' }
99
- } catch {
100
- if ($_.Exception.Message -like '*circular reference*') { throw }
101
- throw "Unable to verify circular references: $($_.Exception.Message)"
102
- }
103
- # Save the completed calculation once. Python verifies every original
104
- # formula's serialized cache and cell type, including errors and missing
105
- # results. Traversing UsedRange through COM duplicates that validation and
106
- # also visits potentially millions of formatted, non-formula cells.
107
- $book.SaveCopyAs($result)
108
- if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
109
- Write-State 'completed'
110
- exit 0
111
- }
112
- catch {
113
- Write-State 'failed' $_.Exception.Message
114
- exit 1
115
- }
116
- finally {
117
- if ($null -ne $book) {
118
- try { $book.Close($false) } catch { }
119
- try { [Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null } catch { }
120
- }
121
- if ($null -ne $excel -and $ownedExcel) {
122
- try { $excel.Quit() } catch { }
123
- }
124
- if ($null -ne $excel) {
125
- try { [Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null } catch { }
126
- }
127
- [GC]::Collect()
128
- [GC]::WaitForPendingFinalizers()
129
- # Quit can leave an orphaned hidden Excel process while COM child ranges
130
- # are being finalized. Ownership is exact: PID + creation timestamp.
131
- if ($null -ne $excelProcess -and $null -ne $excelPid) {
132
- try {
133
- $left = Get-Process -Id ([int]$excelPid) -ErrorAction SilentlyContinue
134
- if ($left -and $left.ProcessName -ieq 'EXCEL' -and
135
- $left.StartTime.ToUniversalTime().ToFileTimeUtc() -eq $excelStartFileTimeUtc) {
136
- Stop-Process -Id ([int]$excelPid) -Force -ErrorAction SilentlyContinue
137
- }
138
- } catch { }
139
- }
140
- }
1
+ [CmdletBinding()]
2
+ param([string]$ParametersPath, [string]$CleanupParametersPath)
3
+
4
+ $ErrorActionPreference = 'Stop'
5
+ $excel = $null
6
+ $book = $null
7
+ $excelPid = $null
8
+ $ownedExcel = $false
9
+ $excelStartFileTimeUtc = $null
10
+ $statePath = $null
11
+
12
+ if (![string]::IsNullOrWhiteSpace($CleanupParametersPath)) {
13
+ try {
14
+ $owned = Get-Content -LiteralPath $CleanupParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
15
+ $p = Get-Process -Id ([int]$owned.pid) -ErrorAction SilentlyContinue
16
+ if ($p -and $p.ProcessName -ieq 'EXCEL') {
17
+ $ft = $p.StartTime.ToUniversalTime().ToFileTimeUtc()
18
+ if ($ft -eq [int64]$owned.startFileTimeUtc) {
19
+ Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
20
+ }
21
+ }
22
+ exit 0
23
+ } catch { exit 1 }
24
+ }
25
+ if ([string]::IsNullOrWhiteSpace($ParametersPath)) { throw 'ParametersPath is required' }
26
+
27
+ if (-not ('XlmergeExcelWindow' -as [type])) {
28
+ Add-Type @"
29
+ using System;
30
+ using System.Runtime.InteropServices;
31
+ public static class XlmergeExcelWindow {
32
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
33
+ }
34
+ "@
35
+ }
36
+
37
+ function Write-State([string]$status, [string]$errorText = $null) {
38
+ if ([string]::IsNullOrWhiteSpace($statePath)) { return }
39
+ $state = [ordered]@{ status = $status }
40
+ if ($null -ne $excelPid) {
41
+ $state.pid = [int]$excelPid
42
+ if ($null -ne $excelStartFileTimeUtc) { $state.startFileTimeUtc = [int64]$excelStartFileTimeUtc }
43
+ }
44
+ if ($null -ne $errorText) { $state.error = $errorText }
45
+ $state | ConvertTo-Json -Compress | Set-Content -LiteralPath $statePath -Encoding UTF8
46
+ }
47
+
48
+ try {
49
+ $parameters = Get-Content -LiteralPath $ParametersPath -Raw -Encoding UTF8 | ConvertFrom-Json
50
+ $source = [IO.Path]::GetFullPath([string]$parameters.source)
51
+ $result = [IO.Path]::GetFullPath([string]$parameters.result)
52
+ $statePath = [IO.Path]::GetFullPath([string]$parameters.state)
53
+ $timeoutSeconds = [int]$parameters.timeoutSeconds
54
+ if ($timeoutSeconds -lt 1) { throw 'timeoutSeconds must be positive' }
55
+ if (!(Test-Path -LiteralPath $source -PathType Leaf)) { throw "Source workbook does not exist: $source" }
56
+ $parent = Split-Path -Parent $result
57
+ if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
58
+
59
+ # Excel constants are used as numbers so this script has no interop assembly
60
+ # dependency. AutomationSecurity=3 is msoAutomationSecurityForceDisable.
61
+ $existingExcelPids = @(Get-Process -Name EXCEL -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
62
+ $excel = New-Object -ComObject Excel.Application
63
+ $window = [IntPtr]$excel.Hwnd
64
+ [uint32]$windowPid = 0
65
+ [XlmergeExcelWindow]::GetWindowThreadProcessId($window, [ref]$windowPid) | Out-Null
66
+ if ($windowPid -eq 0) { throw 'Unable to identify the Excel process created for this calculation' }
67
+ $excelProcess = Get-Process -Id ([int]$windowPid) -ErrorAction Stop
68
+ if ($excelProcess.ProcessName -ine 'EXCEL') { throw 'Excel window belongs to an unexpected process' }
69
+ if ($existingExcelPids -contains $excelProcess.Id) { throw 'Excel COM attached to a pre-existing user Excel process' }
70
+ $excelPid = $excelProcess.Id
71
+ $excelStartFileTimeUtc = [int64]$excelProcess.StartTime.ToUniversalTime().ToFileTimeUtc()
72
+ $ownedExcel = $true
73
+ Write-State 'running'
74
+
75
+ $excel.Visible = $false
76
+ $excel.DisplayAlerts = $false
77
+ $excel.EnableEvents = $false
78
+ $excel.ScreenUpdating = $false
79
+ $excel.AskToUpdateLinks = $false
80
+ $excel.AutomationSecurity = 3
81
+ $excel.UserControl = $false
82
+ # UpdateLinks=0 and ReadOnly=true are positional arguments in the Excel COM
83
+ # API. The temporary source is never saved in place.
84
+ $book = $excel.Workbooks.Open($source, 0, $true)
85
+ # Iterative calculation can make a circular workbook appear to have a
86
+ # stable value. Check after opening the workbook: with no open workbooks,
87
+ # some Excel versions report Application.Iteration as true unconditionally.
88
+ if ($excel.Iteration) { throw 'Workbook enables iterative calculation' }
89
+ $excel.CalculateFullRebuild()
90
+ $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
91
+ while ($excel.CalculationState -ne 0) { # xlDone
92
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation did not reach xlDone before timeout' }
93
+ Start-Sleep -Milliseconds 100
94
+ }
95
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Excel calculation exceeded timeout' }
96
+ try {
97
+ $circular = $excel.CircularReference
98
+ if ($null -ne $circular) { throw 'Workbook contains a circular reference' }
99
+ } catch {
100
+ if ($_.Exception.Message -like '*circular reference*') { throw }
101
+ throw "Unable to verify circular references: $($_.Exception.Message)"
102
+ }
103
+ # Save the completed calculation once. Python verifies every original
104
+ # formula's serialized cache and cell type, including errors and missing
105
+ # results. Traversing UsedRange through COM duplicates that validation and
106
+ # also visits potentially millions of formatted, non-formula cells.
107
+ $book.SaveCopyAs($result)
108
+ if (!(Test-Path -LiteralPath $result -PathType Leaf)) { throw 'Excel did not produce a result file' }
109
+ Write-State 'completed'
110
+ exit 0
111
+ }
112
+ catch {
113
+ Write-State 'failed' $_.Exception.Message
114
+ exit 1
115
+ }
116
+ finally {
117
+ if ($null -ne $book) {
118
+ try { $book.Close($false) } catch { }
119
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($book) | Out-Null } catch { }
120
+ }
121
+ if ($null -ne $excel -and $ownedExcel) {
122
+ try { $excel.Quit() } catch { }
123
+ }
124
+ if ($null -ne $excel) {
125
+ try { [Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null } catch { }
126
+ }
127
+ [GC]::Collect()
128
+ [GC]::WaitForPendingFinalizers()
129
+ # Quit can leave an orphaned hidden Excel process while COM child ranges
130
+ # are being finalized. Ownership is exact: PID + creation timestamp.
131
+ if ($null -ne $excelProcess -and $null -ne $excelPid) {
132
+ try {
133
+ $left = Get-Process -Id ([int]$excelPid) -ErrorAction SilentlyContinue
134
+ if ($left -and $left.ProcessName -ieq 'EXCEL' -and
135
+ $left.StartTime.ToUniversalTime().ToFileTimeUtc() -eq $excelStartFileTimeUtc) {
136
+ Stop-Process -Id ([int]$excelPid) -Force -ErrorAction SilentlyContinue
137
+ }
138
+ } catch { }
139
+ }
140
+ }