Function Search-NestedDirectory($path,$files) {
foreach($childItem in (Get-ChildItem -literalPath $path -force | Sort-Object -property FullName)) {
if($childItem.PSIsContainer -eq "True") {
Write-Host ("Scanning: " + $childItem.FullName) -foregroundColor Green
if($files.count -ge 1) {
Write-Host ("Files Found: " + $files.count)
}
$files = Search-NestedDirectory $childItem.FullName @($files)
} elseif($childItem.Extension -eq ".xls" -or $childItem.Extension -eq ".doc" -or $childItem.Extension -eq ".ppt" -or $childItem.Extension -eq ".txt") {
$file = New-Object -typeName PSObject
Add-Member -inputObject $file -type NoteProperty -name "path" -value $childItem.FullName
Add-Member -inputObject $file -type NoteProperty -name "name" -value $childItem.Name
Add-Member -inputObject $file -type NoteProperty -name "type" -value $childItem.Extension
Add-Member -inputObject $file -type NoteProperty -name "bytes" -value $childItem.Length
Add-Member -inputObject $file -type NoteProperty -name "creationTime" -value ($childItem.CreationTime).ToString()
$files += $file
}
}
return $files
}
$files = Search-NestedDirectory "C:\" @()
$files | Export-Csv -path "files.csv" -noTypeInformation
Wednesday, January 12, 2011
Searching for Files in Nested Directories
Sometimes I need more fine grained control over searching for files in nested directories than the "-recurse" option for Get-ChildItem provides or I don't want to write some extremely long piped command to achieve the desired result. Below is a code snippet that is a good jumping off point to achieving that goal. This snippet will search the C: drive for Office documents and text files and output them to a comma separated value file. You could swap the local path to a UNC path and search a network share.
Labels:
File System,
PowerShell
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment