1

I am trying to change dates programmatically in a file. The line I need to fix looks like this:

    set @@dateto = '03/15/12'

I need to write a powershell V2 script that replaces what's inside the single quotes, and I have no idea how to do this.

The closest I've come looks like this:

    gc $file | ? {$_ -match "set @@dateto ="} | % {$temp=$_.split("'");$temp[17] 
     =$CorrectedDate;$temp -join ","} | -outfile newfile.txt

Problems with this: It gives an error about the index 17 being out of range. Also, the outfile only contains one line (The unmodified line). I'd appreciate any help with this. Thanks!

0

1 Answer 1

1

You can do something like this ( though you may want to handle the corner cases) :

$CorrectedDate = '10/09/09'
gc $file | %{ 
    if($_ -match "^set @@dateto = '(\d\d/\d\d/\d\d)'") { 
        $_ -replace $matches[1], $CorrectedDate; 
    }  
    else {
        $_
    } 
} | out-file test2.txt
mv test2.txt $file -force
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response- Just having one problem with it- It is not changing in the outfile. I'm just getting a copy of $file (I skipped the mv line for now) Let me know what I need to correct. Thanks again for your help!
Found the problem- it was on me. I had the date in there as 1/5/13, so the date pattern it should have been matching was \d/\d/\d\d. I went and prepended 0's to the two numbers, it works like a charm. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.