try {
# Generate unique GUIDs for MMF and EventWaitHandle
$mmfID = [System.Guid]::NewGuid().ToString()
$evntID = [System.Guid]::NewGuid().ToString()
Write-Host "Generated MMF ID: $mmfID"
Write-Host "Generated EventWaitHandle ID: $evntID"
# Create an EventWaitHandle for synchronization BEFORE starting the second script
$evnt = [System.Threading.EventWaitHandle]::new($false, `
[System.Threading.EventResetMode]::AutoReset, "Global\$evntID")
# Create the Memory-Mapped File (MMF) before calling the second script
$mmf = [System.IO.MemoryMappedFiles.MemoryMappedFile]::CreateOrOpen("Global\$mmfID", 1024)
# Start the second script and pass both IDs as arguments
$secondScriptPath = ".\second.ps1" # Adjust path if necessary
Start-Process -FilePath "powershell.exe" -ArgumentList `
"-File `"$secondScriptPath`" `"$mmfID`" `"$evntID`"" -NoNewWindow
Write-Host "Waiting for data from second script... (Timeout: 60s)"
# Wait for event signal (timeout after 60 seconds)
if (-not $evnt.WaitOne(60000)) {
throw "Timeout: No data received within 60 seconds."
}
Write-Host "Data received. Reading from Memory-Mapped File..."
# Create a view stream for reading data
$stream = $mmf.CreateViewStream()
$reader = [System.IO.StreamReader]::new($stream)
# Read the JSON data from the MMF
$jsonRead = $reader.ReadLine()
if (-not $jsonRead) {
throw "Error: No data found in memory-mapped file."
}
# Try to parse the JSON data
try {
$pgpDeTaskInfo = $jsonRead | ConvertFrom-Json
} catch {
throw "Error parsing JSON data: $_"
}
Write-Host "Successfully received and parsed JSON data:"
Write-Host $pgpDeTaskInfo
} catch {
Write-Host "An error occurred: $_" -ForegroundColor Red
} finally {
# Ensure cleanup of resources
if ($reader) { $reader.Close() }
if ($stream) { $stream.Close() }
if ($mmf) { $mmf.Dispose() }
Write-Host "Resources cleaned up."
}