I am writing a script that will log the changes to the modification date of a specific file. I only care about the single newest file. I want to capture that and save its name and Lastwritetime
to a text file.
I am only finding results limiting recursion.
Is there a way to limit the number of results?
To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.
The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the Recurse parameter to get items in all child containers and use the Depth parameter to limit the number of levels to recurse.
Using the Where-Object and Select-Object commands allows you to easily control which items you are working on in PowerShell. You can use these commands to either filter the data you are viewing or to limit actions (such as stopping services or removing files) to those that match the filters you define.
Use the Get-ChildItem cmdlet in PowerShell to get the files in the folder using the file filter and using the Select-Object cmdlet to get the full path of the file using ExpandProperty FullName.
You can use the Select-Object:
Get-ChildItem . | Select-Object -last 1
If you want the latest file, something like:
Get-ChildItem . | Sort-Object LastWriteTime | select -last 1
And of course you can get only the properties that you are interested in with Select-Object as well:
Get-ChildItem . | Sort-Object LastWriteTime | Select-Object -last 1 Name,LastWriteTime
And you can pipe that to Export-Csv.
Aliases can also be used, Get-ChildItem
→ gci
, Select-Object
→ select
, and Sort-Object
→ sort
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With