25 October, 2021

A quick way to make a PoSh Array with a header

I am not really satisfied with how one is 'expected to create arrays in PoSh'...
The conventional methods look pretty, but I find them inflexible...
And I just don't like the way the result behaves... 

PSCustomObjects are a pain in the ass IMO... But I digress.

Here are some methods to look at, and an expanded example of how I use this approach to easily create multidimensional arrays:


$ThisX = @('one','two','nine') | Select @{n='Numbers';e={$_}}
$ThisX
$ThisX.Gettype() | Select IsPublic, IsSerializable, Name,BaseType | fl 

# ~ Result ~

# Numbers
# -------
# one    
# two    
# nine

# IsPublic       : True
# IsSerializable : True
# Name           : Object[]
# BaseType       : System.Array

#####################################

$ThisY = @('one') | Select @{n='Numbers';e={$_}}
$ThisY
$ThisY.Gettype() | Select IsPublic, IsSerializable, Name,BaseType | fl 

# ~ Result ~

# Numbers
# -------
# one

# IsPublic       : True
# IsSerializable : False
# Name           : PSCustomObject
# BaseType       : System.Object

####################################

$ThisZ = @('one')
$ThisZ
$ThisZ.Gettype() | Select IsPublic, IsSerializable, Name,BaseType | fl 

# ~ Result ~

# one

# IsPublic       : True
# IsSerializable : True
# Name           : Object[]
# BaseType       : System.Array

####################################

$This0 = "
zero,0
one,1
two,2
three,3
four,4
five,5
six,6
"
$This0 = ($This0).Split("`n|`r",[System.StringSplitOptions]::RemoveEmptyEntries)

$This0 = $This0 | Select @{n='Number';e={"$(($_).Split(',')[0])"}}, @{n='digit';e={[int]($_).Split(',')[1]}}, @{n='binary';e={[Convert]::ToString(([int]($_).Split(',')[1]),2)}}, Random

$This0.Gettype() | Select IsPublic, IsSerializable, Name,BaseType | fl 

$This0 

# ~ Result ~

# IsPublic       : True
# IsSerializable : True
# Name           : Object[]
# BaseType       : System.Array


# Number digit binary Random
# ------ ----- ------ ------
# zero       0 0            
# one        1 1            
# two        2 10           
# three      3 11           
# four       4 100          
# five       5 101          
# six        6 110  

################################

$This0 | % { $_.Random = 65..90|%{[char]$_}|Get-Random }


# Number digit binary Random
# ------ ----- ------ ------
# zero       0 0           E
# one        1 1           N
# two        2 10          I
# three      3 11          L
# four       4 100         Y
# five       5 101         T
# six        6 110         Z

No comments:

Post a Comment