0

I am trying to compose a script/one liner, which will find files which have been modified over 10 hours ago in a specific folder and if there are no files I need it to print some value or string.

Get-ChildItem -Path C:\blaa\*.* | where {$_.Lastwritetime -lt (date).addhours(-10)}) | Format-table Name,LastWriteTime -HideTableHeaders"

With that one liner I am getting the wanted result when there are files with modify time over 10 hours, but I also need it to print value/string if there are no results, so that I can monitor it properly. The reason for this is to utilize the script/one liner for monitoring purposes.

knob
  • 1

1 Answers1

1

Those cmdlet Get-ChildItem and where clause you have a would return null if nothing was found. You would have to account for that separately. I would also caution the use of Format-Table for output unless you are just using it for screen reading. If you wanted a "one-liner" you would could this. All PowerShell code can be a one liner if you want it to be.

$results = Get-ChildItem -Path C:\blaa\*.* | where {$_.Lastwritetime -lt (date).addhours(-10)} | Select Name,LastWriteTime; if($results){$results}else{"No files found matching criteria"}

You have an added bracket in your code, that might be a copy artifact, I had to remove. Coded properly would look like this

$results = Get-ChildItem -Path "C:\blaa\*.*" | 
    Where-Object {$_.Lastwritetime -lt (date).addhours(-10)} | 
    Select Name,LastWriteTime

if($results){
    $results
}else{
    "No files found matching criteria"
}
Community
  • 1
  • 1
Matt
  • 45,022
  • 8
  • 78
  • 119
  • Thank you bro! This seemed to do the trick, and yea I am only interested in screen reading since the monitoring platform seeks if a certain string in there or not. – knob Sep 02 '16 at 12:21