Public/Export-CustomReport.ps1

Function Export-CustomReport{
    <#
        .SYNOPSIS
        Export an object and store it on the local disk in .CSV format.
 
        .DESCRIPTION
        This function receives an object in input, and save it as a .CSV file on you desired path.
        Positive point for this function is generating a new file name based on date and time to prevent any overwriting.
        If you do not define a path, this function will create 'Report' folder in user profile root and stores report in this location.
 
        .EXAMPLE
        PS> Get-Service | Export-CustomReport -FileName "AllServices"
        Report saved in: C:\Users\User01\Reports\AllServices_03.15.2024_10-01-33.csv
 
        .EXAMPLE
        PS> Get-Service | Export-CustomReport -FileName "AllServices" -Path "C:\Reports"
        Report saved in: C:\Reports\AllServices_03.15.2024_10-04-00.csv
    #>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline=$true)]
        $Object,

        [Parameter(Mandatory = $true)]
        [String]$FileName,

        [String]$Path = $null
    )

    begin{
        $output = @()
        $savePath = $Path
        Write-Verbose -Message "Start to export report ..."
    }

    process{
        $output += $Object
    }

    end{
        try {

            if ([String]::IsNullOrEmpty($savePath)){
                $savePath = Join-Path -Path  $env:USERPROFILE -ChildPath "Reports"
            }

            Write-Verbose -Message "Generating unique file name ..."
            $date = (Get-Date).ToString().Split(" ")
            $uniqueName = $date[0].Replace("/",".") + "_" + $date[1].Replace(":","-")
            $FileName = $FileName + "_" + $uniqueName

            if ($false -eq (Test-Path -Path $savePath) ){
                New-Item -Path $savePath -ItemType Directory | Out-Null
            }

            $path = "$savePath\$FileName.csv"
            $output | Export-Csv -Path $path  -NoTypeInformation -Encoding UTF8 -Force
            Write-Output "`nReport saved in: $path`n"
        }
        catch {
            Write-Error $_
        }
    }
}