Ondrej Skopal
Ondrej Skopal

Reputation: 1

Powershell change file

I am very new in powershell, I hope someone will help me:

I have a file in C:\tmp\appFiles.appcache

Which contains:

CACHE MANIFEST
Version: 2019-01-04T00:48:08.3070330+01:00
Use from network if available
NETWORK:

I need to make a script to change date + time to actual time

For example:

CACHE MANIFEST
Version: 2019-01-19T13:55:08.3070330+01:00
Use from network if available
NETWORK:

Thank you for any help.

Upvotes: 0

Views: 61

Answers (3)

user6811411
user6811411

Reputation:

  • To have a complete date string according to the given format with part seconds and UTC offset
  • replace the Version string with a positive lookbehind RegEx
  • save to same file name (requires reading to memory first)

## Q:\Test\2019\01\18\SO_54255102.ps1
$File = 'C:\tmp\appFiles.appcache'

$Date = Get-Date -f 'yyyy-MM-dd\THH:mm:ss.fffffffzzzzz' # or simply (Get-Date -f o)
(Get-Content $File) -Replace '(?<=^Version: ).*$',$Date | Set-Content $File

Upvotes: 0

Theo
Theo

Reputation: 61263

Or use Select-String and the 'Round-trip date/time pattern' 'o'
See Standard Date and Time Format Strings

$path    = 'C:\tmp\appFiles.appcache\YOUR-FILENAME'
$content = Get-Content $path
$match   = $content | Select-String -Pattern 'Version:' -SimpleMatch -List
if ($match) {
    $content[$match.LineNumber - 1] = "Version: {0}" -f (Get-Date -Format 'o')
    $content | Set-Content -Path $path
}

Upvotes: 1

Bernard Moeskops
Bernard Moeskops

Reputation: 1283

This really is not a script writing service. But if you promise me you will learn more about PowerShell and start trying to understand the following script, I will give you this to work with. Protip: when learning PowerShell you should use PowerShell ISE and press cntrl + R so you have a better way to write and understand PowerShell.

$path = "path to your file"
$content = Get-Content $path
$date = Get-Date -Format s
foreach($row in $content){
    if($row -match "Version:"){
        $newContent = $content.replace("$row","Version: $date+01:00")
    }
}
$newContent | Set-Content $path

The above script gets the content of the file given, then takes the current date. It then searches each row of the content for a mathing text. When found it replaces that specific line with the custom line we created. Then we take the new content and set it to the file we specified. You basically overwrite the whole file this way!

Upvotes: 0

Related Questions