What’s the best way to create a custom object in PowerShell without using CSV?

0
13
Asked By CuriousCoder93 On

I'm trying to create a custom object in PowerShell that functions similarly to a spreadsheet, allowing me to use entries later on in my script. Normally, I'd just use a CSV file for this, but I want everything to be contained within the script itself. I've come up with a method that works, but I feel like it might be unnecessarily complicated. Here's what I currently have:

function MyFunc {
param(
$Name,
$Description
)
[PSCustomObject]@{
Name = $Name
Description = $Description
}
}

$Item = New-Object -TypeName System.Collections.ArrayList
$Item.Add($(MyFunc -Name ABC -Description Alpha)) | Out-Null
$Item.Add($(MyFunc -Name 123 -Description Numeric)) | Out-Null

4 Answers

Answered By PowerScribe On

Where are you getting the parameters like ABC and 123 from? Just curious how you're sourcing them within your script.

CuriousCoder93 -

The parameters are just hardcoded examples in the script. I want to keep everything self-contained, so it's all included directly in the .ps1 file.

Answered By CodingAce On

I usually skip defining a separate function. Instead, I collect all the items and then use a splat to add them. It keeps things simple, and you can definitely create a similar function if you want.

Answered By TechNinja On

Since you might need the properties later, it's a bit tricky to give precise advice without knowing your full plan. Just a heads up: you might want to switch from ArrayList to Generic Lists since ArrayLists are being phased out. Here's a simpler alternative:

```
$List = [System.Collections.Generic.List[PSCustomObject]]::new()
$List.add([PSCustomObject]@{ Name = 'ABC'; Description = 'Alpha' })
$List.add([PSCustomObject]@{ Name = 123; Description = 'Numeric' })
```

This way, you can easily manipulate the list later on, plus it's more efficient in PowerShell. It looks a lot cleaner too!

CuriousCoder93 -

Thanks for the tip! I'll definitely try this approach since it seems more straightforward. I like the idea of using foreach loops with it!

Answered By ScriptMaster01 On

You've got the right idea! Using a PSCustomObject for your properties works perfectly fine. There are multiple ways to do it, and what you've done is good. Just keep in mind that it's all about what you find most convenient.

QuickThinker22 -

I appreciate the confirmation! I was just concerned there might be a simpler way, since this feels a bit elaborate for something that seems straightforward. But I'm glad to know this is a solid solution!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.