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.
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.
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 byGet-ChildItem
will then be passed one by one to another command.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.
Sort by date, descending, so the newest folder is the first one.
Select the first (newest) folder.
So in short:
or
Both of those lines make heavy use of default aliases for commands in PowerShell, such as
?
forWhere-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 theWhere
:Generally you will work with objects and their properties in PowerShell. Two very helpful commands are
Get-Member
and its aliasgm
andGet-Command
or justgcm
.Get-Member
will tell you what properties and methods an object has; you just pipe something else into it for that: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 inObject
you can trygcm *-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.