none
Regular expressions with dates and multiple matches RRS feed

  • Question

  • I am currently attempting to automate modifying start and end dates within a .config file via powershell but I am having issues identifying the regular expression for the end date section since both are on the same line in the file. Below is the string that I want to change.

    • Sometimes the dates are blank and sometimes the dates are filled in.
    • Dates are always in the same format (yyyy-MM-dd hh:mm).
    • I also want to note that there are multiple instances of 'StartDate="" EndDate=""' for other applications throughout the same config file so I cannot limit the expression to not include the App name. 
    • I do not want to limit the search to a line number since there are instances where admins will add an extra space in the config file that may throw off the line number.

    I want to replace the dates or lack there of in their respective spots on the line below via powershell:

     <App name="TestApp" StartDate="2012-03-22 13:30" EndDate="">

    I am successfully able to use 

    $startRegex = '(?<=<App name="TestApp" StartDate=")([^"]*)'

    to replace the StartDate but I can't seem to single out the EndDate with regular expression. What expression can I use to have it ignore what is in the quotations after StartDate and only pay attention to the EndDate value?

    Below is a snippet: 

    $path = d:\inetpub\website\app.config

    $startRegex = '(?<=<App name="TestApp" StartDate=")([^"]*)'

    $starttime = (get-date).ToString("yyyy-MM-dd hh:mm")

    (gc $path) -replace $startregex, $starttime | set-content $path

    I want to accomplish the same for EndDate.

    Thanks in advance!


    • Edited by Faye8 Thursday, April 23, 2015 2:00 PM Corrected Start Regex
    Thursday, April 23, 2015 12:43 PM

Answers

  • If you do this with XML it will be painless and less prone to error.

    $n=$xml.SelectSingleNode('//App[@name="TestApp"]')
    $n.StartDate=$newstartdate
    $n.EndDate=$newenddate

    $xml.Save($filename)


    \_(ツ)_/

    • Marked as answer by Faye8 Thursday, April 23, 2015 8:12 PM
    Thursday, April 23, 2015 2:02 PM

All replies

  • If you do this with XML it will be painless and less prone to error.

    $n=$xml.SelectSingleNode('//App[@name="TestApp"]')
    $n.StartDate=$newstartdate
    $n.EndDate=$newenddate

    $xml.Save($filename)


    \_(ツ)_/

    • Marked as answer by Faye8 Thursday, April 23, 2015 8:12 PM
    Thursday, April 23, 2015 2:02 PM
  • Genius. Didn't even dawn on me that the config was in XML. Thanks!

    Thursday, April 23, 2015 8:13 PM
  • It is generally always easier and safer to use the XML.


    \_(ツ)_/

    Thursday, April 23, 2015 11:30 PM