PowerShell 7.3 - implementing Converting CSV Data into Custom Objects with Nested Properties
I've spent hours debugging this and I'm upgrading from an older version and I've been struggling with this for a few days now and could really use some help....... I'm relatively new to this, so bear with me. I'm struggling to convert a CSV file into custom PowerShell objects where some properties require nested objects. The CSV I'm working with looks like this: ```csv Name,Address,Phone John Doe,"123 Main St, Anytown, USA","(555) 123-4567" Jane Smith,"456 Elm St, Othertown, USA","(555) 987-6543" ``` I want to create a custom object for each row where 'Address' is another object containing 'Street', 'City', and 'Country' as properties. I've tried using `ConvertFrom-Csv`, but I'm running into issues when I attempt to split the address into its components. Hereβs what Iβve done so far: ```powershell $csvData = Get-Content -Path "C:\path\to\your\file.csv" | ConvertFrom-Csv $customObjects = foreach ($row in $csvData) { $addressParts = $row.Address -split ', ' [PSCustomObject]@{ Name = $row.Name Address = [PSCustomObject]@{ Street = $addressParts[0] City = $addressParts[1] Country = $addressParts[2] } Phone = $row.Phone } } ``` However, I'm getting an behavior when trying to access `Country` because sometimes the CSV has unexpected blank fields. The behavior message is: ``` Index was outside the bounds of the array. ``` I suspect that when there is no country provided, `$addressParts` might not have three elements, which leads to the scenario. How can I safely handle varying formats in the CSV data while ensuring I only create nested objects when the data is complete? Any best practices for this scenario would be appreciated! I've considered using `try-catch`, but I'm unsure how to implement it effectively in this context. My development environment is Windows. Thanks in advance! For context: I'm using Powershell on macOS. Has anyone else encountered this? What's the best practice here? What's the correct way to implement this? My development environment is Debian. Any ideas how to fix this? I'd be grateful for any help.