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.