Functions/Data/Add-HistoryLog.ps1

Function Add-HistoryLog
    {
    [CmdletBinding()]
    Param
        (
        #
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [psobject]
        $Data,
        
        # Path to Log file (can include extension)
        [Parameter(Mandatory=$true)]
        [string]
        $FilePath,

        # Data Format for Log
        [Parameter(Mandatory=$False)]
        [ValidateSet("CSV","JSON")]
        [string]
        $Type = "CSV",

        # Max Records in Log
        [Parameter(Mandatory=$false)]
        [int]
        $Tail,

        # Optionally Strip out double quotes from output
        [Parameter(Mandatory=$false)]
        [switch]
        $StripQuotes = $true
        )

    Begin
        {
        # Look for existing file at this path
        $TEST = Test-Path -Path $FilePath
        [array]$HistoryData = if ($TEST)
            {
            switch ($Type)
                {
                "CSV" {[pscustomobject[]](Import-Csv -Path $FilePath)}
                "JSON" {[pscustomobject[]](Get-Content -Path $FilePath | ConvertFrom-Json)}
                }
            }
        else {@(); Write-Host "Log Not Found: Created A New Log!"-ForegroundColor Green}
        # Create Special ArrayList
        if($HistoryData)
            {$HistoryDataObj = [system.collections.arraylist]::new([array]$HistoryData)}
        else
            {$HistoryDataObj = [System.Collections.ArrayList]::new()}
        }

    Process
        {
        # Add new Data to File
        $ADD = $HistoryDataObj.Add($Data)
        }

    End
        {
        # Enforce Tail settings if Applicable
        if ($Tail){$HistoryDataObj = $HistoryDataObj | select -Last $Tail}

        # Export changed History to file based on Type Specified
        switch ($Type)
            {
            "CSV" 
                {
                switch ($StripQuotes)
                    {
                    $true {$HistoryDataObj | ConvertTo-Csv -NoTypeInformation | foreach {$_ -replace '"',''} | Out-File $FilePath -Encoding utf8}
                    $false {$HistoryDataObj | Export-Csv $FilePath -NoTypeInformation -Encoding UTF8}}
                    }
                
                
            "JSON" {$HistoryDataObj | ConvertTo-Json | Out-File $FilePath}
            }
        }
    }