Emre Beloz
Emre Beloz

Reputation: 51

Get name or path of folder if it's empty

I am working on a script, that checks if there is a txt-file inside every subfolder. That works fine, but how is it possible to get the name of the subfolder, if there is no txt-file in it?

For example: Inside "C:\Files\" I have some subfolders A, B, C and D. Inside these subfolders, there is just one txt-file, generated and placed from another software. These files are replaced every day with a new txt-file.

Sometimes one or more files are missing, so the subfolder is empty. How do I get the foldername, if the folder contains no txt-file?

My code:

Check if file from yesterday exists

$yesterday = Get-ChildItem C:\Files\*.txt -Recurse | Where-Object {
    $_.LastWriteTime.ToShortDateString() -eq (Get-Date).AddDays(-1).ToShortDateString()
}

When file is missing:

if (!$yesterday) {
    Send-MailMessage 
        -To $mailReceiver 
        -Cc $mailReceiverCc 
        -From "$mailSenderName $mailSender" 
        -Subject "Backup error" 
        -Body "Backup from yesterday is missing!" 
        -SmtpServer $mailSmtpServer
}

Upvotes: 0

Views: 106

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200533

Enumerate directories and filter for those that don't contain .txt files less than a day old.

$limit = (Get-Date).AddDays(-1)
Get-ChildItem -Recurse | Where-Object {
    $_.PSIsContainer -and
    -not (Get-ChildItem $_.FullName -Filter '*.txt' | Where-Object {
        $_.LastWriteTime -gt $limit
    })
} | Select-Object -Expand FullName

On PowerShell v3 and newer you can simplify that to

$limit = (Get-Date).AddDays(-1)
Get-ChildItem -Recurse -Directory | Where-Object {
    -not (Get-ChildItem $_.FullName -Filter '*.txt' | Where-Object {
        $_.LastWriteTime -gt $limit
    })
} | Select-Object -Expand FullName

Upvotes: 1

Related Questions