How to extract substring from string

rated by 0 users
This post has 3 Replies | 2 Followers

Not Ranked
Posts 3
Diego Posted: 04-04-2012 9:12 AM

Hello!

I'm trying extract a substrings from strings to compare with current date. For exemplo:

$str = "teste_20120404_11h00min00seg"

How to extract "20120404" from $str ?

I tried

$str.Split("_") | Select-String [0-9]

but the result is

20120404
11h00min00seg

Thanks!

Top 25 Contributor
Posts 335
Microsoft MVP
Top Contributor

$str.split("_")[1]  will get you the date

Not Ranked
Posts 3

Thank you very much!

Not Ranked
Posts 3

Hello guys!

I wrote a script to delete some files from a directory and I'd like share with you. The filenames selected by script have the substring ".bak" and a substring that references a date (p.e., "teste_script_20120404.bak") after the second "_" (underscore) - $dtfile variable in the script. If the date in the filename is lesser than current date and the length of $dtfile is greater than zero, the file is deleted.


$year = get-date -uformat "%Y%m%d";
echo $year;
ls | ForEach-Object{echo $_.name} | Select-String ".bak" > ToDel.txt;
$files = cat ToDel.txt;
ForEach ($name in $files) {
   $dtfile = $name.Split("_")[2];
   if(($dtfile -lt $year) -and ($dtfile.Length -gt 0)) {
      #echo $name;
      rm $name;
   }

}

I hope that be useful for someone else!

 

Page 1 of 1 (4 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.