MBF
MBF

Reputation: 366

Powershell For Loop In Reverse

I have the following code:

$testString = "abcdef"
for ($ia=$testString.length-1; $ia -gt 0; $ia - 2) {
$testString[$ia]
}

I need output "fedcba" But keep getting "fffffffffff..."

How can I reverse the testString output by each character in this for loop format?

Upvotes: 3

Views: 10681

Answers (4)

js2010
js2010

Reputation: 27423

Another way with a reverse range in the array index. It should really start at length-1, but it's easier this way and it works. I wish I could do [-1..0] ([-1..-100]?).

$teststring = 'abcdef'
$teststring[$teststring.length..0]

f
e
d
c
b
a


-join $teststring[$teststring.length..0]

fedcba


-join $teststring[-1..-$teststring.length]

fedcba

Upvotes: 4

iRon
iRon

Reputation: 23663

Just to make you aware that there is also a static dotnet Reverse method from the [Array] class:

$CharArray = $teststring.ToCharArray()
[Array]::Reverse($CharArray)
$CharArray
f
e
d
c
b
a

Related GitHub purpose: #16644 Add -Reverse parameter to Sort-Object

Upvotes: 2

Peter Kay
Peter Kay

Reputation: 996

You almost got it.

$testString = "abcdef"
for ($ia=$testString.length-1; $ia -ge 0; $ia--) {
$testString[$ia]
}

You can use $ia-- to decrement down and you should get your result. Also, you should use -ge for greater than or equal to 0 as you want to capture index 0 of the array.

Also, vice versa, you can do the following:

$testString = "abcdef"
for ($ia=$testString.length; $ia -gt -1; $ia--) {
$testString[$ia]
}

Both works, but I prefer the second one as it's easier to read.

enter image description here

Upvotes: 4

Rafael Soares
Rafael Soares

Reputation: 66

Why are you using $ia - 2 ?

You need to change that to $ia-- so it decrements one at a time.

Also change $ia -gt 0 to $ia -ge 0 so it reaches the last index.

Upvotes: 3

Related Questions