Reference current drive path in a Foreach loop through drives

Viewed 53

I'm trying to find and log any local PST files on multiple machines, accross all local drives on each machine. I have the code below so far, but I can't get it to run in the context of the root of the current drive in the foreach loop, it just runs in the context of where the script was run from.

If (-not (Test-Path -Path "\\BETH-FS01\F$\PSTBackups")){
    Exit 1
} # check if PC is connected to domain, some laptops aren't always on the VPN
Else{
    #defines the path where to store the log CSV
    $LogPath = "\\BETH-FS01\F$\PSTBackups" 
    $Log = @() #object array to store "PST objects"

    # defining string variable to combine with another string variable later on
    $Ext = ".pst" 
    
    # creates array of local drives on PC
    $Drives = Get-PSDrive -PSProvider 'FileSystem' 

    foreach ($Drive in $Drives) {

        # searches drive for PST files, creates an array of those files,
        # then passes each through to create PST objects
        $Log = ForEach ($PST in ($PSTS = Get-ChildItem -LiteralPath $Drive.Name -Include *.pst -Recurse -Force -erroraction silentlycontinue)){ 
            New-Object PSObject -Property @{
                ComputerName = $env:COMPUTERNAME
                Path = $PST.DirectoryName
                FileName = $PST.BaseName+$Ext
                Size = "{0:N2} MB" -f ($PST.Length / 1mb)
                Date = $PST.LastWriteTime.ToString("yyyy-MM-dd HH:mm")
            } #creates PST object
        }
    }
}
$Name = $env:COMPUTERNAME #define string to use in log path below
$Log | Export-Csv $LogPath\$Name.csv -NoTypeInformation #exports the Log object array to a CSV

To clarify, I'm trying to find out how to reference the fact that if the foreach loop is currently doing the C: drive, it would use the "C:" path as the -path for Get-ChildItem, i.e.:

$PSTS = Get-ChildItem -path "*somehow reference C: drive path*" -Include *.pst -Recurse -Force -erroraction silentlycontinue

Sorry if the code is sloppy, I'm not the best at keeping clean code...

1 Answers

In this line...

$Log = ForEach ($PST in ($PSTS = Get-ChildItem -LiteralPath $Drive.Name -Include *.pst -Recurse -Force -erroraction silentlycontinue)){ 

... you are just passing the drive letter for -LiteralPath, which is not a path.

You need to pass the root path, e. g. "C:\", not just "C" or "C:". The latter only means the current directory on drive C.

This should do the trick:

$Log = ForEach ($PST in ($PSTS = Get-ChildItem -LiteralPath $Drive.Root -Include *.pst -Recurse -Force -erroraction silentlycontinue)){ 
Related