Tuesday, September 10, 2013

Powershell Export-CSV as FileName with Date

Exporting data from powershell in to CSV format is easy. We can use the 'export-csv' cmdlet. However I got stuck trying to append the date to the filename of the CSV.

The tricky bit that I got stuck on was when i tried Get-date I tried like this thinking it would work.
$users | Export-Csv c:\temp\LNCUS-$(Get-Date -format dd-MM-yyyy) .csv -NoTypeInformation  
This failed with the following error


The error happens because the output from Get-Date is not in a string format. To fix this we just need to convert the date format to string by doing the following
$users | Export-Csv c:\temp\LNCUS-$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation

If you find this article useful please leave me a comment or click on an ad to show your support.

7 comments :

  1. thanks for keeping it simple and easy

    ReplyDelete
  2. This got my logs going. Thank you.

    ReplyDelete
  3. Not a problem. Thanks for reading and taking the time to comment.

    ReplyDelete
  4. Hey Joe, thanks for taking the time to put this together. Clear, concise and correct. I appreciate it.

    ReplyDelete
  5. How about storing the Get-date in a variable? That will give a clean look to the script.

    $CurrentDate = Get-Date
    $CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')

    ReplyDelete
  6. $CurrentDate = Get-Date
    $CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')

    ReplyDelete