Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add items to an PowerShell array, and process the array in batches

I have an array with strings:

$Names = @("Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10")

I want to do the following:

I want to have a Skip variable, where I will cut my array in chunks, and want to print my names with 5 seconds in between.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried it by doing the following:

$BatchSkip = 5 


for($i = 0; $i -lt $names.Count; $i += $BatchSkip){
    $tempArray = $names |Select-Object -First $BatchSkip
    foreach ($name in $tempArray)
    {
        write-host $name 
    } Start-Sleep -Seconds 5
}

But this keeps printing the same names. What factor is missing in my code to implement that it ‘loops’ over my array?

>Solution :

If I correctly understood what you are trying to achieve, then this should work:

$Names = @("Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10")

$BatchSkip = 5

for($i = 0; $i -lt $names.Count; $i += $BatchSkip){
    $tempArray = $names[$i..($i+$BatchSkip-1)]
    foreach ($name in $tempArray)
    {
        write-host $name 
    } Start-Sleep -Seconds 5
}

Your tempArray did not contain the correct values of names, since there was no dependence on the loop variable i.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading