1

I have 3 folders and need to check each folder if there are some files in

I did something like this

$directory = "C:\Folder1","C:\Folder2","C:\Folder3" 

$directoryInfo = Get-ChildItem $directory  | Measure-Object
$directoryInfo.count

if($directoryInfo.Count -gt '0')
{ 
    Write-host "Files in folders" -foregroundcolor RED 
} 
Else
{ 
    Write-host "No files here" -foregroundcolor Green 
}

I need to add for each command in and also need to know if there are some "files" in that folder show me that folder in RED like Write-host "Files in folder $directory"

but now I'm lost in this for each command... i know that's not so hard, but...

thanks for any help here

2 Answers 2

1

Pipe the individual directory names to ForEach-Object, then test them for descendant files one by one.

ForEach-Object will automatically bind each input value to $_:

$directory |ForEach-Object {
    $directoryName = Get-ItemPropertyValue -LiteralPath $_ -Name Name
    if(Get-ChildItem -LiteralPath $_ -File){
        Write-Host "Files found in " -NoNewline
        Write-Host $directoryName -ForegroundColor Red
    } 
    else {
        Write-Host "No files found in " -NoNewline
        Write-Host $directoryName -ForegroundColor Green
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your help Mathias, it works perfect just only one question if i have under $directory path like $directory ="C:\aaa\bbb\ccc\ddd" then in result it shows Files found in ddd . so only last "subdirectory" of aaa. Is it possible to show full path?
@Michal Yeah, just change Write-Host $directoryName -ForegroundColor Red to Write-Host $_ -ForegroundColor Red (you can remove $directoryName = Get-ItemPropertyValue -LiteralPath $_ -Name Name entirely if you don't plan on using the name alone)
0

This is a simplified way of what you are trying to do:

$directory = "C:\Folder1","C:\Folder2","C:\Folder3" 

foreach($dir in $directory)
{
    if( (Get-ChildItem $dir | Measure-Object).Count -eq 0)
    {
        "Folder is empty"
    }
    Else
    {
        "Folder is not empty"
    }
}     

Foreach iterates each of the folder here under the $directory and checks the file availability. Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.