Thursday, August 13, 2015

Get latest file from directory

 

I used this script to look at a list of users Home directories to see if people were using them. That way I could question whether that person was even working with us anymore.

This script does NOT do a recursive search. It only searches the directory you supply.

The script takes its input from a text file, dirList.txt in the script. It is one directory per line in the text file.

 

 

$ErrorActionPreference = "SilentlyContinue"

$theContent = Get-Content "C:\Scripts\dirList.txt"

$List = @()

 

ForEach ($theDir in $theContent){

 

 

 

    try

    {

        $thecount = (dir $theDir | measure).Count

       

        If($thecount -eq 0)

        {

            

             $List += [pscustomobject]@{

            'Directory'       = $theDir

            'Dir Object Count' = "0"

            'FileName'        = "Empty Directory"

            'type'            = ""

            'Date'            = ""

            }

        }

            else

        {

        $latest = Get-ChildItem -Path $theDir  -ErrorAction Stop | Sort-Object LastAccessTime -Descending | Select-Object -First 1

 

         $List += [pscustomobject]@{

            'Directory'       = $theDir

            'Dir Object Count' = $thecount

            'FileName'        = $latest.Name

            'type'            = $latest.GetType().Name

            'Date'            = $latest.LastAccessTime

            }

        

        }

 

  

    }

    catch

    {

        $List += [pscustomobject]@{

            'Directory'        = $theDir

            'Dir Object Count' = ""

            'FileName'        = "No Directory or no access"

            'type'            = ""

            'Date'            = ""

            }

    }

 

}

 

$List | Out-GridView

 

 

No comments:

Post a Comment