Get-Drive.ps1 and Get-File.ps1 – Get all local files


Synopsis

The task of iterating through all local files may be not straightforward if there are several drives including removable, network or substituted drives and NTFS reparse points directories. Get-Drive.ps1 and Get-File.ps1 used together may help: Get-Drive.ps1 returns only local physical drives, Get-File.ps1 excludes reparse points.


Examples

# calculate total available free space in GB
(Get-Drive | Measure-Object AvailableFreeSpace -Sum).Sum/1GB

# get paths of all local .bak files
Get-File \ *.bak -Name

Get-Drive.ps1

##
## Author   : Roman Kuzmin
## Synopsis : Get physical drives
##
## Returns System.IO.DriveInfo objects
##
## *) removable, network and subst drives are excluded.
##

$subst = [string](subst)
foreach($d in [System.IO.DriveInfo]::GetDrives()) {
    if ($d.DriveType -eq 'Fixed' -and $subst -notlike "*$($d.Name):*") {
        $d
    }
}

Get-File.ps1

##
## Author   : Roman Kuzmin
## Synopsis : Get all files
##
## Returns System.IO.FileInfo objects or full names.
## -Root: root directory(s); single \ or // denotes all physical drives.
## -Filter: simple file system filter.
## -Name: return full names as strings.
##
## *) requires Get-Drive.ps1.
## *) access errors are silently ignored.
## *) hidden and system files are included.
## *) reparse points directories are excluded.
##

param
(
    [string[]]$Root = '.',
    [string]$Filter = '*',
    [switch]$Name
)

function DirectoryFiles([System.IO.DirectoryInfo]$di)
{
    # ignore errors
    trap {continue}

    # skip a reparse point
    if ($di.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
        return
    }

    # files
    if ($Name) {
        foreach($f in $di.GetFiles($Filter)) {
            $f.FullName
        }
    } else {
        $di.GetFiles($Filter)
    }

    # directories
    foreach($d in $di.GetDirectories()) {
        DirectoryFiles $d
    }
}

if ($Root.Count -eq 1 -and ($Root[0] -eq '\' -or $Root[0] -eq '//')) {
    foreach($d in Get-Drive) {
        DirectoryFiles $d.RootDirectory
    }
} else {
    foreach($d in $Root) {
        DirectoryFiles $d
    }
}

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: