Create custom structure in PowerShell

Create custom structure in PowerShell

Q. How do I create a custom structure in PowerShell to store multiple rows of data?

A. Often in PowerShell you may want to output information about multiple objects and you struggle with various write-output combinations. A better way is to save the values for each object into a custom object which itself is stored inside an array. The array can then be output or used with other cmdlets. In the example below I create an empty array then for each VM I create a custom object containing the VM name, its status and its resource group. I can then output the content of the $VMList with a well formatted table or any other way I need.

$VMList = @()
foreach($VM in $VMs)
{
 ...some calculations
 $VMList += [PSCustomObject]@{"Name"=$VM.Name; "Status"=$VMStatusDetail; "ResourceGroup" = $VM.ResourceGroupName}
}
$VMList

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish