Have you ever had a problem that you wanted to do something with a collection as a whole and you couldn’t? I had this issue several times. Most obvious and most common problem is discovering collection properties. Is there a length property on the collection? Let’s see:
-
(1,2,3,4) | gm -MemberType Property
It returns literally nothing. Why? Because PowerShell assumes you want to get member of elements rather than whole collection. So what should you do? Use unary comma:
-
,(1,2,3,4) | gm -MemberType Property
-
TypeName: System.Object[]
-
Name MemberType Definition
-
—- ———- ———-
-
IsFixedSize Property System.Boolean IsFixedSize {get;}
-
IsReadOnly Property System.Boolean IsReadOnly {get;}
-
IsSynchronized Property System.Boolean IsSynchronized {get;}
-
Length Property System.Int32 Length {get;}
-
LongLength Property System.Int64 LongLength {get;}
-
Rank Property System.Int32 Rank {get;}
-
SyncRoot Property System.Object SyncRoot {get;}
I had problem with that when I was completing my Inventory module. In this module I create two collection types: one is build on top of System.Collections.Hashtable and second is based on System.Collections.ArrayList. I’ve created functions within module to return both types. It was quite easy with hashtable:
-
Import-Csv $Path | ForEach-Object -Begin {
-
$InventoryHash = New-Object PXL.Hash
-
Write-Host -ForegroundColor Yellow “Processing file: $Path”
-
} -Process {
-
Name=$_.Name
-
SN=$_.SN
-
User=$_.User
-
Last=$_.Last
-
Model=$_.Model
-
Batt=$_.Batt
-
MAC = $_.MAC
-
tel = $_.tel
-
InvDate=$_.InvDate
-
})
-
) | Out-Null
-
} -end {
-
Write-Host -ForegroundColor Cyan ‘Done!’
-
$InventoryHash
-
}
With PXL.List I had to use unary comma, otherwise it would return System.Object[] – and that would not contain any of ScriptMethods I had prepared for my type.
-
# return object without unary comma….
-
-end {
-
Write-Host -ForegroundColor Cyan ‘Done!’
-
$InventoryList
-
}
-
$inv = Import–InventoryList
-
Processing file: A:\Inventory\Full.csv
-
Done!
-
$inv.GetType().FullName
-
System.Object[]
-
# same object, this time using unary comma
-
-end {
-
Write-Host -ForegroundColor Cyan ‘Done!’
-
,$InventoryList
-
}
-
$inv = Import–InventoryList
-
Processing file: A:\Inventory\Full.csv
-
Done!
-
$inv.GetType().FullName
-
PXL.List
Object preserved, methods there were I need them – all happy. 🙂 All thanks to unary comma. So if you are fighting with collection and banging your head against the desk – what I did wrong – maybe unary comma is all you need to move on. 🙂