Note that there are some explanatory texts on larger screens.

plurals
  1. POPowershell: How to initialize array of custom objects?
    primarykey
    data
    text
    <p>I'm fairly new to PowerShell, and usually Google or searching forums like these yields the answers I seek - but not this time. So here is my question (generalized from specific task for privacy/security reasons):</p> <p>First, as this leads to my question, I'll start by noting that I've worked with XML a fair bit in Powershell, and like how I can read data from xml files, quickly, into arrays of custom objects. For example, if I had the following XML file:</p> <pre><code>&lt;stuff&gt; &lt;item name="Joe" age="32"&gt; &lt;info&gt;something about him&lt;/info&gt; &lt;/item&gt; &lt;item name="Sue" age="29"&gt; &lt;info&gt;something about her&lt;/info&gt; &lt;/item&gt; &lt;item name="Cat" age="12"&gt; &lt;info&gt;something else&lt;/info&gt; &lt;/item&gt; &lt;/stuff&gt; </code></pre> <p>And if I read it in simply, like this:</p> <pre><code>[xml]$myxml = Get-Content .\my.xml </code></pre> <p>...then I can get to an array of my items like this:</p> <pre><code>[array]$myitems = $myxml.stuff.Item $myitems name age info ---- --- ---- Joe 32 something about him Sue 29 something about her Cat 12 something else </code></pre> <p>So, now MY QUESTION. <strong>How can I create a similar structure of an array of custom objects, and initialize them in my script, WITHOUT reading a file?</strong> Oh, yea, I can do lots of looping and/or lots of creating/initializing individual objects... and then add to an array... one at a time...</p> <p>But it seems there should be a way to perform this creation/initialization in a simpler way. Note that the key here, is that my custom objects have more than 2 elements (otherwise, I'd have used a hash in an instant!).</p> <p>I've even looked at creating a big string of XML, and using Select-XML, but just couldn't get the syntax right (if that was even the right road to be heading down).</p> <p>So, any help here would be much appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload