pxladin
pxladin

Reputation: 35

Is there a reason why .split in PowerShell doesn't work for me?

$fID = Read-Host "Enter URL" 

if($fID -Match "/"){

$fID = $fID.split("/")[1].split(".")[0]

}

$fID[1] 

input: https://split.string.com (for example)

what i want is just "split"

output: nothing

Can anyone help with this?

Upvotes: 2

Views: 1690

Answers (2)

iRon
iRon

Reputation: 23830

To compliment the comprehensive answer from @mklement0 on the actual "why" question:
I would take this from a different angle and start from the host property of the uri class:

# $fID = [uri](Read-Host "Enter URL" )
$fID = [uri]'https://split.string.com'

$fID.Host.Split('.')[0]

yields

 split

Upvotes: 1

mklement0
mklement0

Reputation: 440431

The problem is that separator / splits by every occurrence of / int the input string so that the // in https://split.string.com results in an extra, empty element in the resulting array of tokens (the empty string between the two / chars.), which is what index [1] returns.

In PowerShell [Core] 6+, simply use // as the separator:

PSCore> 'https://split.string.com'.split('//')[1].split('.')[0]
split

This doesn't work in Windows PowerShell, however, because splitting by a single [string] instance isn't supported by the underlying .NET Framework (instead, its individual characters are interpreted as separators).

There, you can simply take the extra, empty element into account and adjust the index accordingly, as Olaf suggests:

WinPS> 'https://split.string.com'.split('/')[2].split('.')[0]
split

Note: Eliminating the empty entry via an optional argument works too, but is both verbose and obscure: 'https://split.string.com'.split('/', [StringSplitOptions]::RemoveEmptyEntries)[1].Split('.')[0]


The alternative is to use PowerShell's regex-based -split operator, which is generally preferable to the [string] type's .Split() method and works in both PowerShell editions:

PS> ('https://split.string.com' -split '//|\.')[1]
split

Regex //|\. matches either (|) string // or a literal . (escaped as \., because . by itself has special meaning in a regex).

See this answer for background information, including why sticking with PowerShell-native features guards against inadvertent behavioral changes due to new .NET method overloads getting introduced later.

Upvotes: 4

Related Questions