Pdf File Information Script with PowerShell

This blog post will cover a PowerShell script that gathers information about PDF files in a directory and its subdirectories. The script is designed to collect the file name, full path, last accessed time, and owner of each PDF file.

Prerequisites


The Script

This script starts by initializing an empty array $array = @().

$array = @()

Next, it uses the Get-ChildItem cmdlet to retrieve a list of files in the specified directory (C:) and its subdirectories that match the "*.pdf" filter. It then selects the Name, Fullname, and Lastaccesstime properties from each file.

$files = Get-ChildItem -Filter "*.pdf" -Path C: -Recurse | Select-Object Name, Fullname, Lastaccesstime

A foreach loop is then used to iterate over the list of files. For each file, it gets the ACL (Access Control List) using the Get-Acl cmdlet and selects only the Owner property.

foreach ($file in $files) {
    $acl = get-acl $file.fullname | Select-Object -ExpandProperty Owner
}

A custom object is then created using [PSCustomObject] to store the ACL, file name, full path, and last accessed time for each file.

$output = [PScustomobject]@{
    acl = $acl
    name = $file.Name
    path = $file.FullName
    lastaccessed = $file.LastAccessTime
}

The custom object is then added to the $array.

$array += $output

How It Works

Sorting and Exporting the Data

The script sorts the $array by file name using the Sort-Object cmdlet.

$array | Sort-object Name

Finally, it exports the sorted array to a CSV file named "D:\pdfs.csv" using the Export-Csv cmdlet. The -force option is used to overwrite any existing file with the same name, and the -NoClobber and -NoTypeInformation options are used to prevent the creation of additional files in the destination directory.

$array | Export-Csv "D:\pdfs.csv" -force -NoClobber -NoTypeInformation

Key Code Snippets

$array = @()
$files = Get-ChildItem -Filter "*.pdf" -Path C: -Recurse | Select-Object Name, Fullname, Lastaccesstime

foreach ($file in $files) {
    $acl = get-acl $file.fullname | Select-Object -ExpandProperty Owner
    $output = [PScustomobject]@{
        acl = $acl
        name = $file.Name
        path = $file.FullName
        lastaccessed = $file.LastAccessTime
    }
    $array += $output
}

$array | Sort-object Name

$array | Export-Csv "D:\pdfs.csv" -force -NoClobber -NoTypeInformation

Usage Examples

This script can be run in PowerShell to gather information about PDF files in a directory and its subdirectories. The output is then exported to a CSV file.

Conclusion

In this blog post, we covered a PowerShell script that collects information about PDF files and exports the data to a CSV file. This script can be modified and extended to suit specific use cases.