I’m trying to identify folders on a data share which haven’t been used in a long time.
My idea was to loop through all folders, and for each folder loop through all files to get the LastAccessedDate. For testing purposes I’m now trying to list all folders and identify the file with the latest LastAccessedDate. However, I only get one result, which isn’t even in the folder I specified.
Probably something simple I’m missing, but would be glad if someone could help me out.
Or, if there’s an easier way to accomplish the same thing, I’d like to hear it.
Here’s my code:
Function Get-Folders
{
Param([string[]]$path)
# Get all subfolders
$folders = Get-ChildItem -Path $path -Recurse -Directory -Force
# Loop through all files in each subfolder and display newest lastaccesseddate
foreach ($folder in $folders)
{
$lastDate = Get-Date "01/01/1970"
$lastFile = $null
$files = Get-ChildItem -Path $folder -File -Force -ErrorAction SilentlyContinue
foreach ($file in $files)
{
if ($file.LastAccessTime -gt $lastDate)
{
$lastFile = $file
$lastDate = $file.LastAccessTime
}
}
Write-Output $lastFile.FullName
Write-Output $lastFile.LastAccessTime
}
}