Reputation:
I'm writing a windows powershell script to open/edit a text file.
It has many records and each record is sorted of comma-separated values (csv):
Steps I want to achieve:
I've just written this code snippet:
$path = "C:\PSFiles\Rec_File_001.txt"
$Filedata = Get-Content $path
$Record01 = $Filedata[0].split(",")
$Record01Date = $Record01[3]
$Record01CurrentDate = Get-Date -format yyMMdd
$Record01 -replace $Record01Date, $Record01CurrentDate
Set-Content $path
Please, any help on this?
Upvotes: 0
Views: 862
Reputation: 53
Hopefully this helps. Run the following commands in powershell:
$(Get-Item ath/filename.extensionfilename).creationtime=$(get-date "2019-10-15T15:45:12.2723844+01:00")
$(Get-Item C:\temp\log\txt.log).creationtime=$(get-date "2019-10-15T15:45:12.2723844+01:00")
Here is an article from Microsoft that explains how to modify the timestamps of a file https://devblogs.microsoft.com/scripting/use-powershell-to-modify-file-access-time-stamps/
Below is a table from that article showing the attributes that involve time that you can modify.
+----------------+----------+-----------------+---------------------------+
| Name | Member | Type | Definition |
+----------------+----------+-----------------+---------------------------+
| CreationTime | Property | System.DateTime | CreationTime {get;set;} |
| LastAccessTime | Property | System.DateTime | LastAccessTime {get;set;} |
| LastWriteTime | Property | System.DateTime | LastWriteTime {get;set;} |
+----------------+----------+-----------------+---------------------------+
Upvotes: 0
Reputation: 23663
Import-CSV $Path -header text1, text2, text3, date, text5 |
Select text1, text2, text3, @{Name="Date"; Expression={Get-Date -format yyMMdd}}, text5 |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1 |
Set-Content $Path
Or:
$data = Import-CSV $Path -header text1, text2, text3, date, text5
$data | ForEach {"Date" = Get-Date -format yyMMdd}
$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content $Path
Upvotes: 0
Reputation: 17347
You are having multiple questions here. I'll address the one that is presented in the title - replacing text in a text file.
The script:
# current date in a new format
$CurrentDate = Get-Date -format yyMMdd
#replace old format
Get-Content -ReadCount 500 -Path C:\PSFiles\Rec_File_001.txt | % {$_ -replace "(0[1-9]|1[012])\d{1,2}(0[1-9]|[12][0-9]|3[01])", "$CurrentDate"} | Set-Content -Path C:\PSFiles_output\Rec_File_001.txt
This takes regexp for date format Date(mmYYdd)
and exchanges it for a new one. An option -ReadCount
limits the number of lines that go via pipe at one time.
Upvotes: 1