Keeran
Keeran

Reputation: 312

Split string in Powershell

I have sth written in a ".ini" file that i want to read from PS. The file gives the value "notepad.exe" and i want to give the value "notepad" into a variable. So i do the following:

$CLREXE = Get-Content -Path "T:\keeran\Test-kill\test.ini" | Select-String -Pattern 'CLREXE'
#split the value from "CLREXE ="
$CLREXE = $CLREXE -split "="
#everything fine untill here
$CLREXE = $CLREXE[1]
#i am trying to omit ".exe" here. But it doesn't work
$d = $CLREXE -split "." | Select-String -NotMatch 'exe'

How can i do this ?

Upvotes: 0

Views: 145

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

-split is a regex operator, and . is a special metacharacter in regex - so you need to escape it:

$CLREXE -split '\.'

A better way would be to use the -replace operator to remove the last . and everything after it:

$CLREXE -replace '\.[^\.]+$'

The regex pattern matches one literal dot (\.), then 1 or more non-dots ([^\.]+) followed by the end of the string $.


If you're not comfortable with regular expressions, you can also use .NET's native string methods for this:

$CLREXE.Remove($CLREXE.LastIndexOf('.'))

Here, we use String.LastIndexOf to locate the index (the position in the string) of the last occurrence of ., then removing anything from there on out

Upvotes: 3

user459872
user459872

Reputation: 24954

@Mathias R. Jessen is already answered your question.

But instead of splitting on filename you could use the GetFileNameWithoutExtension method from .NET Path class.

$CLREXE = "notepad.exe"
$fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($CLREXE) 
Write-Host $fileNameWithoutExtension  # this will print just 'notepad'

Upvotes: 4

Related Questions