1

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 prints 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?

1 Answer 1

1

("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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.