Search code examples
powershellscriptingpowershell-3.0powershell-4.0windows-scripting

PowerShell check if file exists and output parent directory


I really hope this makes sense. There is going to be more to the script, but the snippet provided is what I am having an issue with.

What I am doing is running a script everyday to look for files from the previous day in a specific folder. Sometimes folders are there and are empty, in which case they are deleted. If folders exist, check them for additional files. If files exist, return parent directory name.

Folder 11 is permanent and never changes. Folders within 11 are created daily with names formatted as YYYYDDD (DDD = julian day). If folder YYYYDDD exists, check it for a folder beginning with YYDDD. If a folder beginning with YYDDD exists, check it for files. If any files exist, return parent directory name, which would be YYDDD.

I know my code currently returns the entire path including the file name. I want it to return the BaseName of the parent directory where the files are.

There is additional code that can be ignored. It is for expansion checking other folders for similar files.

$date0 = (Get-Date).ToString("yy") + ((Get-Date).AddDays(-1).DayOfYear).ToString("D3")
$date1 = (Get-Date).ToString("yyyy") + ((Get-Date).AddDays(-1).DayOfYear).ToString("D3")

$path0 = "U:\PShell\Testing\Delete Julian Dates\Test\11\$date1"
$path1 = "U:\PShell\Testing\Delete Julian Dates\Test\12\$date1"
$path2 = "U:\PShell\Testing\Delete Julian Dates\Test\13\$date1"

$checkfiles = Get-ChildItem $path0\"$date0*"\*

if (Test-Path $path0\"$date0*"\*) {
    $checkfiles|
    % { Write-Host $_.FullName }
} else {
   Write-Host "Folder does not exist or is empty." }

Pause

Solution

  • Use Split-Path -Parent to return the parent folder (full path) of a file or folder.

    If you just want the parent folder name, you can use Split-Path -Parent | Get-Item | Select-Object -ExpandProperty Name.

    Alternatively, you could use ($_.FullName.split("\"))[-2]. The [-2] references the second-to-last element in the array of folder names. [-1] would refer to the file name. Might be a little faster depending on how many files you have to iterate through.