SecureFetch.psm1

[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingEmptyCatchBlock', '', Justification = 'WaitOne throws AbandonedMutexException when it acquires a mutex whose last owner exited without releasing it; the lock is then held and the import proceeds.')]
param()
$pwrsImportLock = New-Object System.Threading.Mutex($false, ('Local\pwrs-import-' + $PID))
try { $null = $pwrsImportLock.WaitOne() } catch [System.Threading.AbandonedMutexException] { }
try {
$root = $PSScriptRoot
$tfm = if ($PSVersionTable.PSEdition -eq 'Core') { 'net10.0' } else { 'netstandard2.0' }
if (-not ('Pwrs.Bootstrap.Loader' -as [type])) {
$stage = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'pwrs-load', $PID)
$null = [System.IO.Directory]::CreateDirectory($stage)
$boot = [System.IO.Path]::Combine($stage, 'Pwrs.Bootstrap.dll')
[System.IO.File]::Copy([System.IO.Path]::Combine($root, $tfm, 'Pwrs.Bootstrap.dll'), $boot, $true)
$null = [System.Reflection.Assembly]::LoadFrom($boot)
}
try { $shell = [Pwrs.Bootstrap.Loader]::Load($root, 'SecureFetch', $tfm) }
catch {
if ($tfm -eq 'net10.0' -and [Environment]::Version.Major -lt 8) {
throw ('SecureFetch' + ' needs PowerShell 7.4 or later: its PowerShell 7 half is built against .NET 8, and this is PowerShell ' + $PSVersionTable.PSVersion + ' on .NET ' + [Environment]::Version + '.')
}
throw
}
$shell.GetType('Pwrs.Modules.SecureFetch.PwrsModuleRoot', $true).GetField('Value').SetValue($null, $root)
foreach ($m in Get-Module -All) {
if ($m.ModuleType -eq 'Binary' -and ($m.Path -eq $shell.Location -or $m.Name -like '*SecureFetch.Shell*')) {
Remove-Module -ModuleInfo $m -Force -ErrorAction SilentlyContinue
}
}
try {
Import-Module -Assembly $shell -Force
$reload = $shell.GetTypes() | Where-Object { $_.Name -eq 'PwrsModule' } | Select-Object -First 1
if ($null -ne $reload) { $null = $reload::ReloadNative() }
}
catch {
$inner = $_.Exception
while ($null -ne $inner.InnerException) { $inner = $inner.InnerException }
throw $inner
}
Export-ModuleMember -Cmdlet 'Invoke-SecureFetch' -Alias @()
} finally {
$pwrsImportLock.ReleaseMutex()
$pwrsImportLock.Dispose()
}