Search code examples
arrayspowershellpowershell-4.0excel-automation

How to create an array like this in powershell?


I need to store data like below for TextToColumns Excel automation. I need to implement Code-2 or Code-3 or Code-4 is that any way to achieve? I have more than 350+ data so I cant use Code-1, that's not fair for me.


Code-1: working fine

$var = (1,2),(2,2),(3,2),(4,2),(5,2),(6,2)........(300,2)
$ColumnA.texttocolumns($colrange,1,-412,$false,$false,$false,$false,$false,$true,"|",$var)


Code-2: not Working

$var = @((1,2)..(300,2))
$ColumnA.texttocolumns($colrange,1,-412,$false,$false,$false,$false,$false,$true,"|",$var)


Code-3: not Working

$var = @()
   
#forloop upto 300 
{ $var += ($i,2) }

$ColumnA.texttocolumns($colrange,1,-412,$false,$false,$false,$false,$false,$true,"|",$var)


Code-4: not Working

[array]$var = 1..300 | foreach-object { ,@($_, 2) }
$ColumnA.texttocolumns($colrange,1,-412,$false,$false,$false,$false,$false,$true,"|",$var)

Solution

  • I can't fully explain what happens here but I guess that it is related to the fact that the texttocolumns requires an (deferred) expression rather than an (evaluated) object.

    Meaning that the following appears to work for the Minimal, Reproducible Example from @mclayton:

    $Var = Invoke-Expression ((1..6 |% { "($_, `$xlTextFormat)" }) -Join ',')
    

    And expect the following to work around the issue in the initial question:

    $Var = Invoke-Expression ((1..300 |% { "($_, 2)" }) -Join ',')