Outputs and easy algorithm question Object Oriented

Viewed 45
$a = dir
foreach ($file in $a) 
{
 if (($file.index%2 ) -eq 0) 
                              //Hopefully this function works, supposed to 
                              (Ideally) print every other file 
 {
    Write-Host  $file.name
 } 

} 

The function -eq 0... not sure if that prints out every other file. I do not know exactly how the files are numbered, or how you reference a number to the file. Do you treat every file as an object and number them? Then make a function regarding the numbers made appended to the file?

Fairly new to this, I'm used to html, css.

If you have a more proficient answer, I'm open to the idea too.

2 Answers

Your script almost works.

Removed alias for dir, and sorted results as requested. The -File switch for Get-ChildItem excludes folders. I guess that's what you want, but remove it otherwise.

Since there's not an easy way to get the current position in foreach, I used a for loop instead, but it's the same idea. If you want to try with foreach, you could set a variable to true, and then not (!) it each iteration.

$Path = 'C:\yourpath'

$Files = Get-ChildItem -Path $Path -File |
    Sort-Object -Property 'Name' -Descending

for ($i = 0; $i -lt $Files.Count; $i++) {
    if ($i % 2 -eq 0) {
        Write-Host  $Files[$i].Name
    }
}

If you're using this output further, it's highly recommended to write results to an object rather than the console window.

Why not simply use a for loop and increment the index counter with a value of 2?

for ($i = 0; $i -lt $a.Count; $i += 2) {
    Write-Host  $a[$i].Name
}
Related