Monthly Archive


Test if a string is a palindrome

This is the first in a short series in which I’ll look at some string handling techniques. PowerShell is all about objects but sometimes you just have to work with the basics. In this post I’ll show how to test in a string is a palindrome.


A palindrome is a list of characters that read the same backwards as well as forwards. Radar is a word that is the same when reversed for example – its a simple palindrome. You can have phrases that are palindromes as well.


function test-palindrome {
param (

Write-Verbose -Message "Input string: $teststring"
$cr = $teststring.ToCharArray()

$ca = $cr | where {$_ -match '\w'}

$clnstring = -join $ca
Write-Verbose -Message "Clean string: $clnstring"


$revstring = -join $ca
Write-Verbose -Message "Reversed string: $revstring"

## make test case insensitive
if ($revstring -ieq $clnstring){
else {



There isn’t a method on the string class to reverse a string so convert the string to an array of chars then use Where-object to filter out non-word characters e.g. punctuation. Recreate the input string without the punctuation etc then use the Reverse static method on the array class. Use –join to create the reversed string from the char array.


Use –ieq (force case insensitive comparison) to test if the two strings are equal and return true or false accordingly.


Some simple examples:

PS> test-palindrome -teststring radar

PS> test-palindrome -teststring Radar

PS> test-palindrome -teststring Richard


And testing a phrase:

PS> test-palindrome -teststring "Madam, I'm Adam" -Verbose
VERBOSE: Input string: Madam, I'm Adam
VERBOSE: Clean string: MadamImAdam
VERBOSE: Reversed string: madAmImadaM

PS> test-palindrome -teststring 'The fat cat sat on the mat'

Comments are closed.