Search code examples
powershellicalendar

How can i modify part of a row in file?


I have a file witch contains multiple rows with strings like this:

DTSTART:20190716T180000

DTEND:20190716T180000

I want to modify every DTEND row. I want to replace the 180000 with 190000. The Parts between DTEND: and 180000 are different each time. Does anyone now how I can change the string in powershell?


Solution

  • here's one way to do the job. [grin] it finds a line that starts with DTEND, grabs the timestamp, converts it to a [datetime] object, adds one hour to it, reformats that to the same layout as the original, builds a new line, and then outputs it to the $Results collection.

    the collection can be sent to a file or screen as desired.

    # fake reading in a text file
    #    in real life, use Get-Content
    $InStuff = @'
    DTSTART:20190716T180000
    DTEND:20190716T180000
    '@ -split [System.Environment]::NewLine
    
    $Marker = 'DTEND'
    $HoursToAdd = 1
    
    $Results = foreach ($IS_Item in $InStuff)
        {
        if ($IS_Item -match "^$Marker")
            {
            $Prefix, $OldTimeStamp = $IS_Item.Split(':')
            $NewTimeStamp = [datetime]::ParseExact($OldTimeStamp, 'yyyyMMddTHHmmssss', $Null).
                AddHours($HoursToAdd).
                ToString('yyyyMMddTHHmmssss')
    
            ($Prefix, $NewTimeStamp) -join ':'
            }
            else
            {
            $IS_Item
            }
        }
    
    $Results
    

    output ...

    DTSTART:20190716T180000
    DTEND:20190716T190000