How to read a string and convert it into a Datetime object using Windows Powershell?


I am trying to read a string from a Text file, which is a date in format: 170929(Sep 29):- “yymmdd”, then convert it into datetime object, so that i can add/subtract days from it.

For ex:
        Record A, a001, a002, a003, "170929", aoo4
        Record B, b001, b002, "170929", b003, b004

My purpose is to read that “170929” value, and then change it to the “CurrentDate()” or add/sub days from it. How can i accomplish this in Powershell?

I have written this so far and am stuck:

$path = "C:\powershell1\test001.txt" 
$Filedata = Get-Content $path
$Record01 = (Get-Content $path)[0]


why don’t you call a code in what language you prefer to do it for you-the power only will call the exe on the required files
You want to combine the Get-ChildItem, Import-Csv, ForEach-Object, and Export-Csv cmdlets. All the parts of your task have been solved already. Read up on them and try how far you can get.
Thanks Tomalak! Could you please help me get started with the code. Im a complete newbie. Would appreciate that. Im learning more about the cmdlets.
– sunny238
3 hours ago



$sourcePath = "C:\powershell1\test001.txt"
$resultsPath = "C:\powershell1\results001.txt"

# Import data in to a PowerShell object. Specifying headers because the file does not contain them.
$records = Import-Csv -Path $sourcePath -Header "col1", "col2", "col3", "someDate", "col5", "col6"

# Display the data
Write-Host "BEFORE" -ForegroundColor Cyan
$records | Format-Table

# Loop over the data set
foreach ($record in $records) {
    # Overwrite a value in a column
    $record.someDate = Get-Date

# Display the updated data
Write-Host "AFTER" -ForegroundColor Cyan
$records | Format-Table

# Write the data back to the file. Note that this *includes* the column headings
$records | Export-Csv -Path $resultsPath -NoTypeInformation


thanks gvee! the problem here is that i want to Replace the date shown as string value like:- “170929(yymmdd)” to the CurrentDate() or anyother date. Can this be done with the replace() method ? $path = “C:\powershell1\testfile.txt” $IP_Array = (Get-Content $path)[0].split(“,”) $Record01DateString = $IP_Array[3] $Record01DateReal = [datetime]::ParseExact(“$Record01DateString”, “yymmdd”, $null) $Record01DateReal
– sunny238
2 hours ago
@sunny238 I don’t follow… 170929=29-Sep-2017. What’s that got to do with CurrentDate() (and what is that function)?. I’m not guessing; but you can format the current date with the Format parameter of the Get-Date CmdLet like so: Get-Date -Format "yyMMdd"