0

I have a generated string like this:

$x = jhgkjh**May**-**JUN**ojklkjh-jkl

I want to substitute every occurrence in $x of a month abbreviation with the number of the month. So the result will look like this:

$x = jhgkjh**05**-**06**ojklkjh-jkl

For that I created 2 arrays:

$months = "Jan", "Feb", etc...
$Nmonths = "01", "02" , etc...

This loop doesn't work:

$i = 0
do {
$x = $x.replace('$months[$i]','$Nmonths[$i]')
$i = $i+1
}
until ("$i" -eq "12")
$x

Please help !

2 Answers 2

1

The sample data looks a little odd with respect to the case of the month strings. Can't really tell if it's case sensitive or not, so here's two slightly different solutions. Starting whe a hash table of month abbreviations and numbers:

$Months=@{
Jan = '01'
Feb = '02'
Mar = '03'
Apr = '04'
May = '05'
Jun = '06'
Jul = '07'
Aug = '08'
Sep = '09'
Oct = '10'
Nov = '11'
Dec = '12'
}

Using string.replace()

$string = '$x = jhgkjh**May**-**Jun**ojklkjh-jkl'
foreach ($Month in $Months.Keys)
 { $string = $string.Replace($Month,$Months.$Month)}

Using the -Replace operator

 $string = '$x = jhgkjh**May**-**JUN**ojklkjh-jkl'
 foreach ($Month in $Months.Keys)
 { $string = $string -Replace $Month,$Months.$Month }  

The string.replace() method is faster, but the -Replace operator will be more flexible with regard to case sensitivity.

Either way, the foreach loop should be faster than foreach-object

Sign up to request clarification or add additional context in comments.

Comments

0

Powershell does not have a do until construct. Try this one liner instead of your loop.

0..11 | % { $x = $x -replace $months[$_],$Nmonths[$_] }

The .. Operator creates a range of integers between the first number and the last.

If you still want to use a traditional flow control structure you can replace the until line with this

while($i -lt 12)

3 Comments

Powershell does have a do until construct. Try this: $i=0; do {$i;$i++} until ($i -eq 10)
Wow, egg on my face. Can't believe I have missed that for so stinking long.
Basically the same as While (), but tests at the end of the loop, so it always goes through the loop at least once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.