CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Issues with Custom Object Properties Not Displaying as Expected in Export-CSV

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
powershell csv export PowerShell

I'm stuck on something that should probably be simple. I'm stuck on something that should probably be simple. I'm encountering a frustrating issue while trying to export a custom PowerShell object to a CSV file using `Export-CSV`. After creating a custom object, I add properties to it but when I export it, some properties seem to be missing or not formatted correctly in the resulting CSV. Here's the code I'm using: ```powershell # Creating a custom object $customObject = [PSCustomObject]@{ Name = 'John Doe' Age = 30 Email = 'john.doe@example.com' Active = $true } # Modifying the object by adding a new property $customObject | Add-Member -MemberType NoteProperty -Name 'LastLogin' -Value (Get-Date) # Attempting to export to CSV $customObject | Export-CSV -Path 'output.csv' -NoTypeInformation ``` When I check the `output.csv` file, it only contains the properties `Name`, `Age`, and `Email`. The `LastLogin` property is missing entirely. I've tried both `-Force` and `-Append` parameters with `Export-CSV`, but nothing seems to change. Additionally, I noticed that if I create an array of custom objects and then export that, it works correctly: ```powershell $customObjects = @() $customObjects += $customObject $customObjects[0].LastLogin = (Get-Date) $customObjects | Export-CSV -Path 'output2.csv' -NoTypeInformation ``` That works fine, and all properties are included. It seems like the issue might be related to how I'm modifying the single object before exporting. Is there a best practice or a specific way to ensure all properties of a single custom object are included in the export when using `Export-CSV`? Any help would be greatly appreciated! How would you solve this? For context: I'm using Powershell on macOS. Thanks in advance!