How to sort the output in powershell

11,942

Your "Select-Object -First 1" gives you only the first file, to get all files, remove that. Like so:

$newPath = 'C:\Users\tim\Desktop\tim_test2'
$content = get-childitem 'C:\Users\tim\Desktop\tim_test' | Sort-Object LastWriteTime -Descending
Write-Host $content

# Part 2
$oldFile = $content | Select-Object -first 1
$prefix = Read-Host "Enter prefix"
$newFile = "$newPath\$prefix$oldFile"
Copy $file $newFile

Something like that should work :)

Share:
11,942
user3770612
Author by

user3770612

Updated on June 04, 2022

Comments

  • user3770612
    user3770612 almost 2 years

    I am trying to list the content of a directory and try to sort them out the most recently created folders of file. I am using the following script but it is only giving me 1 item which is most recently created. All I would like to do is list all the folders in asc or desc order

    $content = get-childitem 'C:\Users\tim\Desktop\tim_test'
    write-output $content |  Sort-Object LastWriteTime -Descending | Select-Object -First 1
    
  • user3770612
    user3770612 almost 10 years
    thanks a lot but I forgot to mention in my question that after sorting out I would like to copy the most recent file or folder to a new location but do not know how to do that
  • Erik Blomgren
    Erik Blomgren almost 10 years
    Just added a line for copy part, replace $newLocation with the path you wish to copy the file to
  • user3770612
    user3770612 almost 10 years
    Is there a way to number the output for example if The output is like folder1 folder 2 folder 3 i would like to number them like 1.folder1 2.folder2 because i would like the user to input the number e.g 1 or 2 to copy that folder onto a new location. thanks
  • user3770612
    user3770612 almost 10 years
    can some on please help around with the last post
  • user3770612
    user3770612 almost 10 years
    the above solution lets me add a prefix e.g 1 to a folder which will be copied to a new location, but i want to display the numbers with the folder before copying. or in simple words i could say that i want to display numbering with directory content and based on those number i can ask user to input which folder they want to copy to a new location.
  • user3770612
    user3770612 almost 10 years
    $content = get-childitem 'C:\Users\tim\Desktop\tim_test' write-output $content | Sort-Object LastWriteTime -Descending whatever the output is from this script i want to add numbers with them and based on those numbers i would like to ask user which folder he wants to copy to a new location.
  • user3770612
    user3770612 almost 10 years
    hi i have work around the script but this last line is giving alot of issue this script runs perfect but as soon as i enter the user input say "1" i get an error message copy-item the input object cannot be bound to to any parameter for the command error on this line $sortedContent[$itemNumber] | Copy-Item "newpath"