2

I'm trying to split the filename without extention and assign it to a new variable. But .split('') function adds new whitespace or tab. Any suggestion to fix this?

$dmpfile = "test.dmp"
$filename = $dmpfile.split('.dmp')
echo $filename
test

ls $filename*.log
no output.............
echo $filename*.log
test     *.log
3
  • Corrected typo $filename = $string.split('.dmp') to $filename = $dmpfile.split('.dmp')
    – user
    Nov 12, 2018 at 6:43
  • 3
    [System.IO.Path]::GetFileNameWithoutExtension($dmpfile)
    – user240633
    Nov 12, 2018 at 7:05
  • That worked. split and trim both removes characters in the filename instead of extension. Thanks
    – user
    Nov 12, 2018 at 7:16

2 Answers 2

1

First of all, the split function creates an object with all strings that appear between the split character. You have to access a single item of the property by using $variable[x], where x would be the position of the item you want. In your case you would have to call $filename[0]. (First item is not 1, it starts with 0)

Second, I cannot realy explain why, but if you use the string method split like you did, every single character will be handled as possible delimiter. This is why 'pmdasdfgpmd.dmp'.split(".dmp") will return asdfg - same as if you would use trim. But if you use the function like this:

'pmdasdfgpmd.dmp' -split".dmp"

it will return the filename without extension: pmdasdfgpmd

Third, if you want to remove a part of a string, you can also use the replace method and replace the string by nothing:

either

'test.dmp'.replace(".dmp","")

or

'test.dmp' -replace ".dmp"

But this is just about some basic string replacement in powershell - the easiest way the get the filename without extension is either the way @PetSerAl proposed:

[System.IO.Path]::GetFileNameWithoutExtension($dmpfile)

or you call the Get-Item PSFunction and use the BaseName-Property:

(Get-Item $dmpfile).BaseName

In both cases, the variable $dmpfile must hold the full path to the file, not only the file name.

0

You should use Trim() instead of Split(). $filename = $dmpfile.Trim(".dmp")

1
  • Note that 'pmdasdfgpmd.dmp'.Trim(".dmp") will return asdfg.
    – user240633
    Nov 12, 2018 at 7:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .