1

Windows 10, version 10.0.19042.868

Hello,

I have PowerShell script for selecting first XXX files and moving into another folder.

Get-ChildItem -File *.txt | Sort-Object Name | Select-Object -First 25000 | Move-Item -Destination C:\txtFilesToProcess\

But how to select half of files from Get-ChildItem?

Saibamen
  • 610
  • 3
  • 17
  • 43
  • Get-ChildItem -File *.txt | Sort-Object Name | Select-Object -First (Get-ChildItem -File *.txt).Count/2 | Move-Item -Destination C:\txtFilesToProcess\ – Vivek Kumar Singh Mar 22 '21 at 08:36
  • 6
    @VivekKumarSingh I'd avoid that, because you have double `Get-ChildItem`. Better use variable – filimonic Mar 22 '21 at 08:41

1 Answers1

3

Assign the output of Get-ChildItem to a variable so you know the number of files in advance.

This was the accepted solution:

$files = Get-ChildItem -File *.txt | Sort-Object Name 
$files | Select-Object -First ($files.Count / 2) | Move-Item -Destination C:\txtFilesToProcess\

Alternative way using a single pipeline (more for academic purposes as it makes the code harder to understand):

,(Get-ChildItem -File *.txt) | ForEach-Object {
    $_ | Select-Object -First ($_.Count / 2) | Move-Item -Destination C:\txtFilesToProcess\ -WhatIf
}
  • The parentheses (aka grouping operator) around the Get-ChildItem command collects all output of the command in an array, before proceeding with the next pipeline command.
  • Additionally the comma operator is required as a way to prevent enumeration of the array elements (see this Q&A for details). It creates an array that contains the output array from Get-ChildItem as a single element.
  • Now ForEach-Object operates on the whole Get-ChildItem output array, so we can use $_.Count to get the total number of files.
zett42
  • 25,437
  • 3
  • 35
  • 72