none
Powershell to Parse XML and extract date and compare RRS feed

  • Question

  • I have a backup log which is XML and I would like to parse it to verify the last backup was within the last 24 hours. I have run into problems trying to get my output into the correct format so I can do some sort of compare. I am sure there is much better ways to do this than my code as I am green in PowerShell

    XML:

    <?xml version="1.0" encoding="utf-8"?>
    <machinedetails>
    <QuotaSize>1.82 GB</QuotaSize>
    <FileCount>23518</FileCount>
    <SuccessCount>1524</SuccessCount>
    <AlreadyPresent>21994</AlreadyPresent>
    <FailureCount>0</FailureCount>
    <BackupSize>1.82 GB</BackupSize>
    <LastBackup>11/05/2014 05:00:27 AM</LastBackup>
    </machinedetails>

    PowerShell:

    $Priorday = (Get-Date).AddDays(-1).ToString()
    [xml]$backup = Get-Content "C:\Users\badams\Scripts\backuplog.xml"
    $budate1 = $backup.SelectSingleNode("//LastBackup") | format-table -hidetableheaders
    $budate2 = $budate1 | out-string
    $budate3 = ([datetime]::ParseExact($budate2, "mm/dd/yyyy hh:mm:ss",$null))

    Any help is greatly appreciated!


    Britt

    Wednesday, November 12, 2014 4:22 PM

Answers

  • I think this is more straightforward:


    $lastBackup = ([Xml] (get-content "C:\Users\badams\Scripts\backuplog.xml")).SelectSingleNode("//LastBackup")."#text" -as [DateTime]
    

    This will return $lastBackup as a DateTime object you can compare with $Priorday.

    There is no need to convert to strings.


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Britt Adams Wednesday, November 12, 2014 4:44 PM
    Wednesday, November 12, 2014 4:29 PM
    Moderator

All replies

  • I think this is more straightforward:


    $lastBackup = ([Xml] (get-content "C:\Users\badams\Scripts\backuplog.xml")).SelectSingleNode("//LastBackup")."#text" -as [DateTime]
    

    This will return $lastBackup as a DateTime object you can compare with $Priorday.

    There is no need to convert to strings.


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Britt Adams Wednesday, November 12, 2014 4:44 PM
    Wednesday, November 12, 2014 4:29 PM
    Moderator
  • If your dates and times are always in that format (MM/dd/yyyy hh:mm:ss tt), then you can just cast to DateTime directly, as Bill suggested.

    Try this:

    $yesterday = (Get-Date).AddDays(-1)
    [xml]$backup = Get-Content 'C:\Users\badams\Scripts\backuplog.xml'
    $backupDate = $backup.SelectSingleNode('//LastBackup').'#text' -as [datetime]
    
    if ($backupDate -lt $yesterday)
    {
        # The backup is older than 24 hours ago; take some action
    }
    

    Wednesday, November 12, 2014 4:37 PM
  • Bill,

    Thank you for the quick response, that worked like a charm.  I have a long ways to go with PowerShell.


    Britt

    Wednesday, November 12, 2014 4:46 PM