Powershell – get the latest created folder from a path using powershell

powershell

How to get the latest created folder from a path using Windows PowerShell?

I have the path C:\temp and I want to find the most recently created folder in this path.

Best Answer

PowerShell works mainly with the pipeline, so most of what you'd write will consist of creating objects representing some information, and filtering and manipulating them. In this case, the objects are a bunch of folders.

  1. Get all items in the folder. This will get files and folders, that's why step 2 is necessary. The | at the end of the line signals that the pipeline will continue in the next line – objects created by Get-ChildItem will then be passed one by one to another command.

    Get-ChildItem c:\temp |
    
  2. Filter for folders. There is no really elegant way, sadly. Don't worry about that it says “container”, not “folder” – Those commands work with many different things, not only files and folders, so a more general concept was used in naming.

    Where { $_.PSIsContainer } |
    
  3. Sort by date, descending, so the newest folder is the first one.

    Sort CreationTime -Descending |
    
  4. Select the first (newest) folder.

    Select -First 1
    

So in short:

gci c:\temp | ? { $_.PSIsContainer } | sort CreationTime -desc | select -f 1

or

(gci c:\temp | ? { $_.PSIsContainer } | sort CreationTime)[-1]

Both of those lines make heavy use of default aliases for commands in PowerShell, such as ? for Where-Object. You should use the full names in scripts, though, as you'll never know what the aliases will look like on other machines the code might run on.


EDIT: PowerShell 3 has additional parameters for Get-ChildItem that allow you to do filtering for files or folders directly, so you don't need the Where:

Get-ChildItem -Directory C:\temp | ...

Generally you will work with objects and their properties in PowerShell. Two very helpful commands are Get-Member and its alias gm and Get-Command or just gcm. Get-Member will tell you what properties and methods an object has; you just pipe something else into it for that:

Get-ChildItem | gm

will tell you what properties files and directories have.

Get-Command will list all commands there are or those that match a particular pattern. PowerShell commands try to be very consistent in their use of verbs and nouns. To find all commands that end in Object you can try gcm *-Object – those are general commands working with pretty much everything. Get-Help ForEach-Object then would tell you about a particular command, ForEach-Object in this case.