Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PowerShell consider @() syntax differently

Tags:

powershell

Array initialization works differently in powershell

$scripts = @(
    ("01", "a" , "01_Cleanup")
    ,("02", "b" , "02_Cleanup")
);

Output:

$scripts[0] - "01"
$scripts[1] - "a"
$scripts[2] - "01_Cleanup"
$scripts[3] - "02"
"b"
"02_Cleanup"

Please notice "," in array initialization.:

$scripts = @(
    ("01", "a" , "01_Cleanup"),
    ("02", "b" , "02_Cleanup")
);

Output:

$scripts[0] - "01"
"a"
"01_Cleanup"
$scripts[1] - "02"
"b"
"02_Cleanup"

Why?

like image 435
Shantanu Gupta Avatar asked Apr 29 '26 07:04

Shantanu Gupta


1 Answers

Its because of different usage of the Comma operator (binary vs unary):

As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member.


Binary:

@(
    ("01", "a" , "01_Cleanup"),
    ("02", "b" , "02_Cleanup")
) | foreach { Write-Host $_};

Output:

01 a 01_Cleanup
02 b 02_Cleanup

Unary:

 @(
    ("01", "a" , "01_Cleanup")
    ,("02", "b" , "02_Cleanup")
) | foreach { Write-Host $_};

Output:

01
a
01_Cleanup
02 b 02_Cleanup
like image 99
Martin Brandl Avatar answered May 02 '26 05:05

Martin Brandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!