How do I merge two "lists" in PowerShell when one list might be just one item from Get-Item?
If $myCerts
might just be a single item, use the array subexpression operator @( )
:
$allCerts = @($myCerts) + $trustedPeopleCerts
Another solution that accomplishes the same thing is to use a unary comma operator to ensure that $myCerts
is always an array. Consider the following examples that we are using for one element and 0 elements.
$myCerts = Get-Item C:\temp
$myCerts.GetType().FullName
$myCerts = $null
$myCerts.GetType().FullName
The above would generate System.IO.DirectoryInfo
and an error for "call[ing] a method on a null-valued expression"
Now lets try the same thing with unary comma operator.
$myCerts = ,(Get-Item C:\temp)
$myCerts = ,($null)
The answer in both cases is System.Object[]
I forgot about one thing this is doing. @()
might be preferential in this case as it is an array sub expression. The comma operator I think here is creating a multidimentional array. When used in a pipe it is unrolled and you still get the data you are looking for but it is an important difference to note.