Comparing file last write time to current time

Welcome Forums General PowerShell Q&A Comparing file last write time to current time

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
8 months, 1 week ago.

  • Author
    Posts
  • #94524

    Participant
    Points: 0
    Rank: Member

    I'm using WinSCP PowerShell module from PS Gallery to download file from SFTP Server. I need to throw an error if the file in remote SFTP server is older than 48 hours .

    Currently I'm succesfully reading the lastwritetime from remote file and I can get it in format '02/23/2018 01:10:44'. Now I need to compare it to current time and throw an error if the file is older than 48 hours. My local time format is a little different (dd.mm.yyyy 00:00:00) than what's in remote server. Does it matter and do I need to convert them to same format before comparing? Any help would be appreciated.

  • #94527

    Keymaster
    Points: 1,639
    Helping HandTeam Member
    Rank: Community Hero

    Yeah, casting it as a [datetime] – which is what you would need to do – may break because of your local time format settings. You may end up having to manually parse the remote date into a string based on your local format settings, and then [datetime] cast it.

  • #94542

    Participant
    Points: 0
    Rank: Member
    [datetime]::ParseExact('22.02.2018 22:03:30','dd.MM.yyyy HH:mm:ss',[cultureinfo]::InvariantCulture)

    If the format is consistent, then you can parse it out with ParseExact.

  • #94575
    js

    Participant
    Points: 224
    Helping Hand
    Rank: Participant

    If you could use powershell, it would just be (older than 2 days):

    $a = ls file                                                                                                                   
    if ( (get-date) - $a.LastWriteTime -gt 2. ) { 'do whatever' }       
    
  • #95676

    Participant
    Points: 0
    Rank: Member

    OK I learned something new. Date format is coming in correct format from remote server. Problem was that I was using " Write-output "File modified: $($remoteFile.LastWriteTime)" and this causes date format to change in '02/23/2018 01:10:44' format.

The topic ‘Comparing file last write time to current time’ is closed to new replies.