Looping Question with indexes - Powershell

Christopher Jack 1,611 Reputation points
2021-03-26T10:59:39.83+00:00

Hi,

I am trying to get a loop working for one order - I am having issues because the index of the array starts at 0

$null = For ($i=0; $i -le $OrderNumbers.count-1; $i++) 
{

}

I have tried using a temp variable to say if order numbers .count = 1 to set to two but then that loops through twice once for 0 and once for 1.

I am only wanting it to loop through once for one record.

Any help appreciated

This test does not seem to work at all

 $q = 0
    $t = 1
    $OrderNumbers = @(1,2)
    $OrderNumbers.count
    $x=1
    for ($y=0; $y -le $OrderInfo.count-1; $y++)
    {
        "yo"
        $x++
        $x
    }
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 40,741 Reputation points
    2021-03-26T13:11:06.273+00:00

    $OrderNumbers = @(1,2) … $OrderInfo.count-1

    In the array declaration you use name $OrderNumbers and in the for loop an other name $OrderInfo ; that don't work =>

    $q = 0
    $t = 1
    $OrderNumbers = @(1,2,3,4);
    Write-Host $OrderNumbers.count;
    $x=1;
    for ($y=0; $y -le $OrderNumbers.count -1; $y++)
    {
        Write-Host "yo";
        $x++;
        Write-Host $x;
    }
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 44,776 Reputation points
    2021-03-26T14:31:48.623+00:00

    There's really no need for the For-loop.

    $OrderNumbers = @(1,2)
    $x=1
    $OrderNumbers |
        ForEach-Object{
            Write-Host "OrderNumber: $_" -ForegroundColor Yellow
            "yo"
            $x++
            $x
        }
    
    0 comments No comments