Search code examples
databasepowershellcsvappendrecord

Looking for a better way to record or track when a script runs


I have a powershell script where it does multiptle remote IT supports. To keep track of its usuage, it logs and append the current user's name, date, time, and current computer name to a csv file stored in a network drive. There are about 20 people who use the scripts so potentially, that csv file can try to open and write an entry at the same time.

Is there a better way to do it as I'm sure the csv will corrupt eventually?

Thanks.


Solution

  • In this case I would use EventLog to record the events using Write-EventLog.

    $server = "My-Log-Server" # Log server name or IP
    $eventChannel = "Application" # EventLog. It is possible to choose any existing or create own.
    $provider = "Calculator" # Provider of event. It is possible to choose any existing or create own.
    $eventid = 300 # Id of the event
    
    # Message: current computer, current user, date/time
    $msg = ( $env:COMPUTERNAME, $env:USERNAME, ( Get-Date ).ToString( "yyyy-MM-dd HH:mm:ss" )) -join","
    
    Write-EventLog -ComputerName $server -LogName $eventChannel -Source $provider -EventID $eventid -EntryType Information -Message $msg
    

    Then either

    1. make a scheduled task to collect the events using Get-WinEvent and append records to the csv file or
    2. make an event driven task that would append a record to the csv file.