Public/Export-Earning.ps1
|
function Export-Earning { <# .SYNOPSIS Exports earnings to a file. .DESCRIPTION Exports one or all earnings 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 earning name to export. If omitted, exports all earnings. .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-Earning -OutputPath "earnings.csv" Exports all earnings to a CSV file. .EXAMPLE Export-Earning -Name "Salary" -OutputPath "salary.json" Exports a specific earning to JSON format. .EXAMPLE Export-Earning -OutputPath "C:\Backups\earnings.json" -Format JSON -Budget "MyFamilyBudget" Exports all earnings from a specific budget to JSON. .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 earnings $getParams = @{} if ($Name) { $getParams['Name'] = $Name } if ($Budget) { $getParams['Budget'] = $Budget } if ($DataPath) { $getParams['DataPath'] = $DataPath } $earnings = Get-Earning @getParams if (-not $earnings -or $earnings.Count -eq 0) { Write-Warning "No earnings 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' { $earnings | Select-Object Id, Name, StartDate, Frequency, Amount, Status, Tags, AccountId | Export-Csv -Path $OutputPath -NoTypeInformation -ErrorAction Stop Write-Verbose "Exported $($earnings.Count) earning(s) to CSV: $OutputPath" } 'JSON' { $earnings | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -ErrorAction Stop Write-Verbose "Exported $($earnings.Count) earning(s) to JSON: $OutputPath" } } return (Resolve-Path $OutputPath).Path } catch { Write-Error "Failed to export earnings: $_" } } |