Ian
Ian

Reputation: 299

PowerShell - adding a column to an array

Let’s say you're doing something like this:

$partitions = get-wmiobject -query "Associators of {Win32_DiskDrive.DeviceID=""$DevID""} WHERE AssocClass = Win32_DiskDriveToDiskPartition" -computer $ComputerName

If you then want to get the disk caption for each disk (the 'C:') you need something like this:

function GetDiskCaption {
   param ($Partition, $ComputerName)

    $DeviceID = $Partition.DeviceID
    $colLogicalDisk = get-wmiobject -query "Associators of {Win32_DiskPartition.DeviceID=""$DeviceID""} WHERE AssocClass = Win32_LogicalDiskToPartition" -computer $ComputerName

   If ($colLogicalDisk.Caption -ne $null) {
      return $colLogicalDisk.Caption
   }
   Else {
       return "UNASSIGNED"
   }
}

I'm not a very advanced PowerShell user, so the question is: What's the best PowerShell way to add the disk caption to the array so that can pipe it into, say, ft or some other script?

Now I realise I can just do a foreach loop to print this out, but I want to work out how to extend an array with extra columns so that I can then use piping operators to, say, format the array.

The examples on the Microsoft site on array handling are all based on one-dimensional arrays, so adding arrays does not seem to be the answer.

I'm specifically trying to write a script to dump out the list of disks, with their iSCSI mapping (if any) and the various partitions on that disk.

Upvotes: 2

Views: 21830

Answers (1)

manojlds
manojlds

Reputation: 301177

You can either use a hashtable (associative array):

$hash = @{}
$partitions | %{ $caption = GetDiskCaption $_ $computername; $hash[$caption]=$_ }
$hash

Or create objects:

$combined = $partitions | %{ $caption = GetDiskCaption $_ $computername
                $obj = new-object psobject
                $obj | add-member -name caption -type noteproperty -value $caption
                $obj | add-member -name partition -type noteproperty -value $_
                $obj
            }

Upvotes: 7

Related Questions