Powershell Variable Split – How to Split Variable Without New Line or Spaces

powershell

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

Best Answer

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.