Home > Software engineering >  Output one value in foreach loop in Powershell
Output one value in foreach loop in Powershell

Time:12-03

I am looping through a folder with files, to select some of them accordingly if they match the day that we are currently. I want to output a message if it doesn't file any file that matches the day, but I only what one message to be outputted instead of a message for each file.

Any clues on how to make that happen in my code below:

foreach ($file in Get-ChildItem -Path $directory) {
        
        if ($file.LastWriteTime.Date -eq [datetime]::Today) {
            Write-Output "File from today"

        } else {
            Write-Output "File is not from today"
        } 
   
    }

CodePudding user response:

You can store if you found a a search result in a boolean variable.

$hasFile = $false 
foreach ($file in Get-ChildItem -Path $directory) 
    if ($file.LastWriteTime.Date -eq [datetime]::Today) {
            Write-Output "File from today"
            $hasFile = $true
     }
}

if ($hasFile -eq $false) {
   Write-Output "No file found"
} 
   
    

CodePudding user response:

I think you could approach it this way, first try to find any files from today and, if there are none, then display the message.

Note: I have added the -File switch to find only files, else we would be also looking at folders which would be not intended.

$todayFiles = Get-ChildItem . -File | Where-Object {
    $_.LastWriteTime.Date -eq [datetime]::Today
}

if ($todayFiles) {
    $todayFiles | ForEach-Object { "File from Today => {0}" -f $_.FullName }
} else {
    "File is not from today"
}
  • Related