PowerShell File Search Automation

One of the common requirements when working with files and folders is to get file details at a particular path. For example, searching for all the text files in a specific folder. Often we do it manually or sort it in Windows Explorer. This is one of the tasks which can be easily automated using Powershell.

Powershell has the concept of drives. When working with files and folders, we can use the commandlets for drives. In our case, these cmdlets will let us retrieve and manipulate the files and folders. For example, we can list all the files in a specific folder using the following command:

 Get-ChildItem -Path "Path"

The above command will list the contained items, such as folders or files. You can further filter with the Filer parameter:

This will filter based on the file name. Since we need to display the file details contained within a particular folder, we will define a function for this.

function Get-FolderDetails
{
    # Your code logic here
}

We will pass a parameter called $path and $extension to this function. This will be used to filter the folder based on the files with matching extensions at the provided path.

Get-ChildItem -Path $path -Filter $extension

Also, we want to ensure that the item we are searching in is a folder. To achieve this, we can use the where command.

where {!$_.PSIsContainer}

Now our function looks like this.

function Get-FolderDetails($path, $extension = "*.txt") {
    $files = Get-ChildItem -Path $path -Filter $extension | Where-Object { -Not $_.PSIsContainer }

}

Now we can easily iterate and display the various properties of the filtered files sing the following.

foreach ($object in $file)
{
    Write-Host "`n Name : $($object.Name)"
    Write-Host " Size : $($object.Length)"
    Write-Host " Extension : $($object.extension)"
}

Complete doe will function should is now.

function Get-FolderDetails($path, $extension = "*.txt") {
    $file = Get-ChildItem -Path $path -Filter $extension | where {!$_.PSIsContainer}
    $fileCount = ($file).Count
    Write-Host "`nNumber of files: $fileCount"
    Write-Host "`nFile Details:"
    foreach ($object in $file) {
        Write-Host "`nName: $($object.Name)"
        Write-Host "Size: $($object.Length)"
        Write-Host "Extension: $($object.Extension)"
    }
}

And we can call it.

Get-FolderDetails -extension "*.txt" -path  G:\POCpowershell1

This will display file details for the text files at the specified path.

Path


Similar Articles