How to extract substring from string

rated by 0 users
Not Answered This post has 0 verified answers | 3 Replies | 2 Followers

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


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



All Replies

Top 25 Contributor
350 Posts
Top Contributor

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

Not Ranked
3 Posts

Thank you very much!

Not Ranked
3 Posts

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 $} | 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 All rights reserved.