Windows Server TechCenter > Windows Server Forums > Windows PowerShell > replace text in file using wildcards
Ask a questionAsk a question
 

Answerreplace text in file using wildcards

  • Wednesday, June 24, 2009 11:18 AMmnemonicator Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi there, i have next text in my file *20090623* this is date, i need change this text every day, so i wrote next code

    $getdate_curr=get-date -format yyyMMdd (assign to variable current date in required format) and then i'm trying replace old date to new one

    (Get-Content D:\I\moveit\config.par) |
    Foreach-Object {$_ -replace "2009*\*",$getdate_curr} |
    Set-Content D:\I\moveit\config.par

    It's work incorrectly, how can i change this code?

    Thank you.

Answers

  • Wednesday, June 24, 2009 6:41 PMMarco ShawMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    Check this out:
    $today=get-date -format yyyMMdd
    
    $today
    
    $yesterday=(get-date).adddays(-1)|%{
      if($_.month -lt 10){$month=[string]0+$_.month}else{$month=$_.month}
      if($_.day -lt 10){$day=[string]0+$_.day}else{$day=$_.day}
      [string]$_.year+[string]$month+[string]$day
    }
    
    $yesterday
    
    "$yesterday".replace($yesterday,$today)
    
    Using the format you're looking for to calculate yesterday is a PAIN!  Maybe there's an easier though.

    That should help you out...
    • Marked As Answer bymnemonicator Thursday, June 25, 2009 6:31 AM
    •  

All Replies

  • Wednesday, June 24, 2009 11:56 AMMarco ShawMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Are you always replacing the date from the day before?  I'm thinking you would create a variable for yesterday and today, and then use those variables in the replace to do an exact replacement.
  • Wednesday, June 24, 2009 2:36 PMmnemonicator Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    yes, you are correct. i'll try to do this, it's my first steps in PS...

  • Wednesday, June 24, 2009 6:41 PMMarco ShawMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    Check this out:
    $today=get-date -format yyyMMdd
    
    $today
    
    $yesterday=(get-date).adddays(-1)|%{
      if($_.month -lt 10){$month=[string]0+$_.month}else{$month=$_.month}
      if($_.day -lt 10){$day=[string]0+$_.day}else{$day=$_.day}
      [string]$_.year+[string]$month+[string]$day
    }
    
    $yesterday
    
    "$yesterday".replace($yesterday,$today)
    
    Using the format you're looking for to calculate yesterday is a PAIN!  Maybe there's an easier though.

    That should help you out...
    • Marked As Answer bymnemonicator Thursday, June 25, 2009 6:31 AM
    •  
  • Thursday, June 25, 2009 6:31 AMmnemonicator Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    thank you so much.