Public/Export-Account.ps1
|
function Export-Account { <# .SYNOPSIS Exports accounts to a file. .DESCRIPTION Exports one or all accounts from a budget to CSV or JSON format. .PARAMETER OutputPath The file path for the export. Extension determines format (.csv or .json). .PARAMETER Name Optional account name to export. If omitted, exports all accounts. .PARAMETER Format Output format: CSV or JSON. If not specified, determined by file extension. .PARAMETER Budget Optional budget name to target. Uses active budget if not specified. .PARAMETER DataPath Optional custom path for data storage. Overrides budget-based paths. .EXAMPLE Export-Account -OutputPath "accounts.csv" Exports all accounts to a CSV file. .EXAMPLE Export-Account -Name "Chase Checking" -OutputPath "chase.json" -Format JSON Exports a specific account to JSON format. .EXAMPLE Export-Account -OutputPath "C:\Backups\accounts.csv" -Budget "MyFamilyBudget" Exports all accounts from a specific budget to CSV. .OUTPUTS File path of the exported data #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$OutputPath, [Parameter()] [string]$Name, [Parameter()] [ValidateSet('CSV', 'JSON')] [string]$Format, [Parameter()] [string]$Budget, [Parameter()] [string]$DataPath ) # Get accounts $getParams = @{} if ($Name) { $getParams['Name'] = $Name } if ($Budget) { $getParams['Budget'] = $Budget } if ($DataPath) { $getParams['DataPath'] = $DataPath } $accounts = Get-Account @getParams if (-not $accounts -or $accounts.Count -eq 0) { Write-Warning "No accounts found to export." return } # Determine format from file extension if not specified if (-not $Format) { $extension = [System.IO.Path]::GetExtension($OutputPath).ToLower() $Format = switch ($extension) { '.json' { 'JSON' } '.csv' { 'CSV' } default { 'CSV' } } } # Ensure directory exists $directory = Split-Path -Path $OutputPath -Parent if ($directory -and -not (Test-Path $directory)) { New-Item -Path $directory -ItemType Directory -Force | Out-Null } # Export based on format try { switch ($Format) { 'CSV' { $accounts | Select-Object Id, Name, Bank, Last4Digits | Export-Csv -Path $OutputPath -NoTypeInformation -ErrorAction Stop Write-Verbose "Exported $($accounts.Count) account(s) to CSV: $OutputPath" } 'JSON' { $accounts | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -ErrorAction Stop Write-Verbose "Exported $($accounts.Count) account(s) to JSON: $OutputPath" } } return (Resolve-Path $OutputPath).Path } catch { Write-Error "Failed to export accounts: $_" } } |