2

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

1 Answer 1

3

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 :)

Sign up to request clarification or add additional context in comments.

7 Comments

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
Just added a line for copy part, replace $newLocation with the path you wish to copy the file to
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
can some on please help around with the last post
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.