Private/Get-SecureCredential.ps1
|
function Get-SecureCredential { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Target ) $credential = $null $osType = Get-OperatingSystemType if ($osType -eq 'Windows') { Write-CustomLog -Message "Using Windows Credential Manager for: $Target" -Severity 'DEBUG' if (-not (Get-Command -Name 'Get-StoredCredential' -ErrorAction SilentlyContinue)) { try { Import-Module -Name 'CredentialManager' -ErrorAction Stop } catch { Write-CustomLog -Message "Failed to import CredentialManager module: $($_.Exception.Message)" -Severity 'DEBUG' } } if (-not (Get-Command -Name 'Get-StoredCredential' -ErrorAction SilentlyContinue)) { throw "Windows Credential Manager support requires the 'CredentialManager' PowerShell module. Install it with: Install-Module -Name CredentialManager -Scope CurrentUser" } $credential = Get-StoredCredential -Target $Target } elseif ($osType -eq 'macOS') { Write-CustomLog -Message "Using macOS Keychain for: $Target" -Severity 'DEBUG' $credential = Get-MacOSKeychainCredential -ServiceName $Target } else { throw "Unsupported operating system. Only Windows and macOS are supported." } if ($null -eq $credential) { throw "Credential '$Target' not found" } return $credential } function Get-OperatingSystemType { [CmdletBinding()] param() if ($IsWindows -or $env:OS -eq 'Windows_NT') { return 'Windows' } elseif ($IsMacOS) { return 'macOS' } else { return 'Unknown' } } function Get-MacOSKeychainCredential { [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param( [Parameter(Mandatory = $true)] [string]$ServiceName ) try { $account = & security find-generic-password -s $ServiceName -g 2>&1 | Select-String -Pattern '"acct"<blob>="([^"]*)"' | ForEach-Object { $_.Matches.Groups[1].Value } $passwordOutput = & security find-generic-password -s $ServiceName -w 2>&1 if ($LASTEXITCODE -ne 0) { Write-CustomLog -Message "Credential not found in macOS Keychain: $ServiceName" -Severity 'DEBUG' return $null } Write-CustomLog -Message "Retrieved credential from macOS Keychain: $ServiceName" -Severity 'DEBUG' $securePassword = ConvertTo-SecureString -String $passwordOutput -AsPlainText -Force return [PSCredential]::new($account, $securePassword) } catch { Write-CustomLog -Message "Error retrieving credential from macOS Keychain: $_" -Severity 'DEBUG' return $null } } |