Powershell script Logging format

Azure-learning 56 Reputation points
2022-10-27T19:17:39.75+00:00

I am trying to create a function for logging , it's giving me output log.csv file as below format.

date=10:28:2022 log_type=info stauts=success
date=10:28:2022 log_type=info stauts=failure
date=10:28:2022 log_type=info entity=failure

below is the function code I am using-
function Logs($type,$status))
{
$date = get-date -Format "MM:dd:yyyy"
"date=$date" + " , " + "log_type=$type" , " + "status=$status" | Out-File "logging.csv" -Append

if ( $type -eq "error")  
    {  
        Write-Host ""  
    }...  

}

but I want csv file to be with a column heading (date, log_type, status). How to change above function so that csv file will generate in column name format.
as below example -

date log_type status
10/28 info success
10/28 info success

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2022-10-27T19:50:11.077+00:00

    Hi @NGaur-3476 ,

    you can just add this line to create the column heading to the file:

    # To add the column heading to an existing file  
    Out-File "logging.csv" -Append -InputObject "Date log_type status"  
    # To add the column heading to a new file  
    Out-File "logging.csv" -InputObject "Date log_type status"  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

  2. Rich Matheisen 47,901 Reputation points
    2022-10-27T21:19:25.763+00:00

    Instead of working with strings, concatenation, placing commas in quotes, etc., you could do this:

    function Logs{  
        param(  
            $type,  
            $status  
        )  
        [PSCustomObject]@{  
            date        = Get-Date -Format "MM:dd:yyyy"  
            log_type    = $type  
            status      = $status  
        } | Export-CSV logging.csv -NoTypeInformation -Append  
      
        if ($type -eq "error") {  
            Write-Host ""  
        }...  
    }  
    

    Just to make a point, your function contains an error: "date=$date" + " , " + "log_type=$type" , " + "status=$status" -- it's missing a concatenation operation and a double-quote.

    You can accomplish the same thing like this: "date={0} , log_type={1} , status={2} -f $date, $type, $status" | Out-File logging.csv -Append -- without all the quoting and concatenation.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.