Scripting Question

Hi Guys,

I have following powershell script meant to return file last modified datetime if it is older than certain timestamp. I ran it against two computers. However, despite the fact that file is older than certain value on only 1 computer, it writes both computer in the resulting HTML file.
Is there a way to output only one computer name when it is older than certain timestamp.

$body = 'IIS Log file information'
$CurrentTime = Get-Date
$CurrentTime.AddMinutes(-15)
$query1 = "Select * from CIM_Datafile WHERE Drive='C:' AND Path='\\PShell\\MyDirectory\\' AND FileName='IISlogs'"
$FileName = Get-WmiObject -Query $query1 -ComputerName SQL01,DC01 | Select Name, @{Label="LastModified";expression={($_.ConvertToDateTime($_.LastModified))}}, PSComputerName
ForEach-Object{ If (($FileName.LastModified) -lt $CurrentTime.AddMinutes(-15).ToShortTimeString()) {
$Body +=  "ModifiedTime  of $($FileName.Name) on $($FileName.PSComputerName)  is  old"
ConvertTo-Html -Body $Body    | Out-File C:\Output.html 
        }
else {
Write-Host "ModifiedTime of filenames are correct" -ForegroundColor DarkMagenta 
    }
}

OR
it is the only way to do it via Where-Object (shown below) method instead of Foreach-Object (shown above).

$body = 'IIS Log file information'
$CurrentTime = Get-Date
$CurrentTime.AddMinutes(-15)
$query1 = "Select * from CIM_Datafile WHERE Drive='C:' AND Path='\\PShell\\MyDirectory\\' AND FileName='IISlogs'"
$FileName = Get-WmiObject -Query $query1 -ComputerName SQL01,BQLDC01 | Select Name, @{Label="LastModified";expression={($_.ConvertToDateTime($_.LastModified))}}, PSComputerName
$FileName | Where-Object {$_.LastModified -lt $CurrentTime.AddMinutes(-15)} | Select-Object Name, PSComputerName, LastModified  | ConvertTo-Html -Body $body | Out-File C:\Output1.html

Once it is done, i want to invoke Send-MailMessage cmdlet to send email if file is older than certain timestamp value.

Thanks
Aleem

ForEach or Where will perform about the same. But you’re using ForEach-Object incorrectly; it’s meant to accept piped input and you’ve not given it any.

To troubleshoot this, I’d probably move to a more script-like form and add some debugging:

ForEach ($File in $FileName) {  
 Write-Debug "Last modified is $($file.lastmodified) and is a date: $($file.lastmodified -is [datetime])"
 Write-Debug "Is less than 15 minutes ago: $()"

As a partial example. You’re also mangling your data types. If you’re going to compare dates and times, you need them to be DateTime objects. But here:

ForEach-Object{ If (($FileName.LastModified) -lt $CurrentTime.AddMinutes(-15).ToShortTimeString()) {

You’re forcing a string from the current time minus 15 minutes. I think your logic is just fine, here, but you’re getting the syntax wrong.