You can pipe the output of the ConvertTo-Html cmdlet to the Out-File cmdlet to write the html code to a file. For example:
} | ConvertTo-Html -CssUri html.css | Out-File -FilePath Events.html
About the 'object not found' error when you call the writedata function, as I wrote in my first answer, you have to define the writedata function before you use it. So move the function definition to the beginning of your script. Remember that PowerShell is a shell and not a compiled programming language. You can only use what you have defined before.