PowerShell array, loop first row

Viewed 44

i have a problem with array as following with only one line:

$list = @()
$list =  (("ResourceGroup","Vm1"))


$list | ForEach-Object -Parallel {

    write-output $_[0] $_[1]

}

if i loop that array with one line,powershell print the first 2 letter of each word. If i put 2 or more row like following:

    $list = @()
    $list =  (("ResourceGroup","Vm1"),`
              ("ResourceGroup","Vm2")
)

powershell print correctly the values inside.

There is a way to print correctly the value of an array with only one line?

Thanks

1 Answers

("ResourceGroup","Vm1") is interpreted as one array with two string elements, where as (("ResourceGroup","Vm1"), ("ResourceGroup","Vm2")) is interpreted as one array with 2 array elements, can be also called a jagged array. If you want to ensure that the first example is treated the same as the second example, you can use the comma operator ,:

$list = , ("ResourceGroup","Vm1")
$list | ForEach-Object -Parallel {
    Write-Output $_[0] $_[1]
}

To put it in perspective:

$list = ("ResourceGroup","Vm1")
$list[0].GetType() # => String

$list = , ("ResourceGroup","Vm1")
$list[0].GetType() # => Object[]

Write-Output with the -NoEnumerate switch combined with the Array subexpression operator @( ) can be another, more verbose, alternative:

$list = @(Write-Output "ResourceGroup", "Vm1" -NoEnumerate)
$list | ForEach-Object -Parallel {
    Write-Output $_[0] $_[1]
}
Related