0

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 ?

asked Sep 20, 2021 at 12:07
1
  • 2
    -split is a regex operator, you need to escape .: $CLREXE -split '\.' Commented Sep 20, 2021 at 12:09

2 Answers 2

4

@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'
answered Sep 20, 2021 at 12:23

1 Comment

This is in my opinion a more stable and generic solution as a filename actually could contain more than one '.' in the name...
3

-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

answered Sep 20, 2021 at 12:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.