Home > OS >  Files in folders (powershell script)
Files in folders (powershell script)

Time:08-31

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

CodePudding user response:

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
    }
}

CodePudding user response:

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.

  • Related