Search code examples
arrayswindowspowershellscriptingpowershell-5.0

LastAccessTime of the very last accessed File of an array of Folder


I'd like to get an overview of the latest accessed file per profile directory out of a list of profile directories and then write the result in a file.

Given:

A folder with a ton of profile directories in it. In every profile directory, there are more folders and files.

Wanted:

I need the date with the name of the profile directory of the latest accessed file of each profile directory within the parent folder.

What I already have:

With the following commands, the output file lists the last accessed file out of all files in the whole directory times the count of profile directories in the folder:

cd \\Servername\Patch\Profiles
$folder = Get-ChildItem -Directory
$folder | ForEach-Object {
  Get-ChildItem -Recurse |
    Sort-Object -Property LastAccessTime -Descending |
    Select-Object -First 1
} | Out-File "C:\Users\User-abc\Desktop\Log.txt"

So I tried to add the specific path for each profile folder within the parent folder to the Get-ChildItem command like this:

... ForEach-Object {
  Get-ChildItem -Path ".\$folder" -Recurse |
    Sort-Object ...

I also tried to add a .Name to the $folder variable and to remove the " or put ' instead of ", but nothing helped. I always get the response that there is no parameter found for the parameter -Path. I also tried to remove the -Path parameter but let the .\$folder or even add a [0] or [1] to the $folder variable, but that also doesn't help.


Solution

  • Call Get-ChildItem on the full path of the current object in the pipeline:

    Get-ChildItem \\Servername\Patch\Profiles -Directory | ForEach-Object {
      Get-ChildItem $_.FullName -Recurse |
        Sort-Object -Property LastAccessTime -Descending |
        Select-Object -First 1
    }