Resources for IT Professionals > 論壇首頁 > Windows PowerShell > replace text in file using wildcards
發問發問
 

已答覆replace text in file using wildcards

  • 2009年6月24日 上午 11:18mnemonicator 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.

解答

  • 2009年6月24日 下午 06:41Marco ShawMVP, 版主使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     已答覆包含代碼
    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...

所有回覆

  • 2009年6月24日 上午 11:56Marco ShawMVP, 版主使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    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.
  • 2009年6月24日 下午 02:36mnemonicator 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     

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

  • 2009年6月24日 下午 06:41Marco ShawMVP, 版主使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     已答覆包含代碼
    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...
  • 2009年6月25日 上午 06:31mnemonicator 使用者勳章使用者勳章使用者勳章使用者勳章使用者勳章
     
    thank you so much.