Por algum motivo, o powershell não me deixa converter a string[]
em an object[]
, mas permite para todos os outros tipos. O exemplo abaixo mostra que funciona para vários tipos, exceto string.
[int[]]$intary = 2,4
[char[]]$chrary = 'a','b'
[bool[]]$booary = $true,$false
[DateTime[]]$datary = (Get-Date),(Get-Date)
[string[]]$strary = 'c','d'
$splary = 'e,f' -split ',' # -split returns [string[]] type specifically
[object[]]$objaryi = @()
[object[]]$objaryc = @()
[object[]]$objaryb = @()
[object[]]$objaryd = @()
[object[]]$objarys = @()
[object[]]$objarysp = @()
$intary.GetType() # Int32[]
$chrary.GetType() # Char[]
$booary.GetType() # Boolean[]
$datary.GetType() # DateTime[]
$strary.GetType() # String[]
$splary.GetType() # String[]
$objaryi.GetType() # Object[]
'conversions'
$objaryi = $intary # Int32[] converted to Object[]
$objaryi.GetType() # Object[]
$objaryc = $chrary # Char[] converted to Object[]
$objaryc.GetType() # Object[]
$objaryb = $booary # Boolean[] converted to Object[]
$objaryb.GetType() # Object[]
$objaryd = $datary # DateTime[] converted to Object[]
$objaryd.GetType() # Object[]
$objarys = $strary # NOT converted to Object[]; instead changes type of $objarys to String[]
$objarys.GetType() # String[]
$objarysp = $splary # NOT converted to Object[]; instead changes type of $objarysp to String[]
$objarysp.GetType() # String[]
$objarys = @($strary) # the array subexpression operator @() DOES convert to Object[]
$objarys.GetType() # Object[]
$objarysp = @($splary) # the array subexpression operator @() DOES convert to Object[]
$objarysp.GetType() # Object[]
'inline cast'
$objarys = @([string[]]@(1,2)) # the array subexpression operator @() does not work on an inline cast [1]
$objarys.GetType() # String[]
Uma razão pela qual isso importa é que se você tentar armazenar um hash em um array que é tipado, string[]
o powershell converterá silenciosamente sua definição de hash para uma string. A string é o sting para o caminho completo typename do hash.
$objaryi[0] = @{a=1;b=2} # can hold a hashtable because it's now an Object[]
$objaryi[0].GetType() # Hashtable
$objaryi[0]['b'] # 2
$objarys[0] = @{a=1;b=2} # silently converts to a string because it's a String[]
$objarys[0].GetType() # String
$objarys[0]['b'] # $null; perhaps unexpected
$objarys[0] # the String value "System.Collections.Hashtable"
$objarys[0].Length # 28