Lessons in PowerShell - Looping Through File Folders

   Submit to Reddit      
  

One way in PowerShell to get a collection of file folders is by using the .NET System.IO.Directory.GetDirectories function. Time is short, and I am familiar with that, so I will use the .NET library in this example script.

Here is one way in which it can be done.

$folders=[System.IO.Directory]::GetDirectories("c:\xxxx")

foreach ($folderName in $folders)
{                
    ...
}

If we wanted to, within the loop we could instantiate a System.IO.DirectoryInfo object to give us more information about the folder.

$folder = New-Object System.IO.DirectoryInfo($folderName)                    

And then we can access the properties on that class, like the folder's LastWriteTime in order to find out how old it is.

Here is a complete script.

$now = Get-Date
$yesterday = $now.AddDays(-1)
$folders=[System.IO.Directory]::GetDirectories("c:\program files")                    

foreach ($folderName in $folders)                    
{
    $folder = New-Object System.IO.DirectoryInfo($folderName)

    if ($folder.LastWriteTime -lt $yesterday)                    
    {                     
        Write-Host("Folder " + $folderName + " is at least a day old")                    
    }
    else
    {
        Write-Host("Folder " + $folderName + " is less than a day old")
    }                    
}


comments powered by Disqus