Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If / Else in Powershell not behaving as expected?

Tags:

powershell

Can someone explain to me why below is not working as expected? In the below example, I would expect the $shortFQDN variable to be set as test.com, but I'm getting back www.test.com:

$fqdn = 'dev.www.test.com'
$d3 = $fqdn.Split('.')[-3] #www
$d2 = $fqdn.Split('.')[-2] #website
$d1 = $fqdn.Split('.')[-1] #com

#Check if this is a 2LD domain (.com.au, .co.uk, .co.jp, etc.)
if ($d1 -ne 'com' -or 'net' -or 'org' -or 'edu' -or 'gov' -or 'biz') {
    $shortFQDN = -join ("$d3",'.',"$d2",'.',"$d1")
} else {
    $shortFQDN = -join ("$d2",'.',"$d1")
}

What am I doing wrong? It seems like the if/else is not processing correctly...

like image 203
Dominic Brunetti Avatar asked Jun 03 '26 22:06

Dominic Brunetti


1 Answers

Your if() is wrong. Although you can say in English "if a is not b or c or d, then...", in virtually all programming languages - and scripting languages - you need to say "if a is not b and a is not c and a is not d, then...".

Rather than redoing the $fqdn.Split() three times and subscripting the result each time, just take the output from the first time, and assign it to a variable, then simply subscript the variable.

Also, PowerShell allows you to use ranges, much like some dialects of Pascal, and you can use the -match operator with regular expressions. I'd rewrite your code as

$fqdn = 'dev.www.test.com'
$d = $fqdn.Split(".")    # or $d = $fqdn -split "\."
$tlds = "com|net|org|edu|gov|biz"
if ( -not ($d[-3] -match $tlds) ) {
    $shortfqdn = $d[-3..-1] -join "."
} else {
    $shortfqdn = $d[-2..-1] -join "."
}
like image 115
Jeff Zeitlin Avatar answered Jun 06 '26 05:06

Jeff Zeitlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!