Search code examples
powershellcmd

how to copy files CMD or Powershell with condition always ignore two files


I want to copy files from a specific folder with a condition that always ignores two files until the last file.

Example: Copy file 1, next 4, next 7, next 10 ...


Solution

  • To get 1 item from a collection, then skip two, then repeat, use the modulo (%) operator to calculate every third index:

    # Enumerate files in folder
    $files = Get-ChildItem .\folder -File
    
    # Based on the count, calculate the array indices for every 3rd file
    $indices = 0..($files.Count - 1) |Where-Object { $_ % 3 -eq 0 }
    
    # Assign every 3rd file to new array
    $filesToCopy = $files[$indices]
    

    Now you can copy only those files:

    $filesToCopy |Copy-Item .\destination\