DarkLite1
DarkLite1

Reputation: 14705

PowerShell TrimStart not always working

I'm trying to trim the beginning of a string, but it doesn't always work correctly with TrimStart(). In the first example below it works fine, but in the second it doesn't.

Correct result:

$Array = 'C:\Users\boblee\AppData\Local\Temp\2\Beez\ISO\ISO\Environnement',
'C:\Users\boblee\AppData\Local\Temp\2\Beez\ISO',
'C:\Users\boblee\AppData\Local\Temp\2\Beez\ISO\Achat'
$Array | % {$_.TrimStart('C:\Users\boblee\AppData\Local\Temp\2')}

Wrong result:

$Array = 'S:\Test\Bob\Out_Test\Beez\ISO\ISO\Environnement',
'S:\Test\Bob\Out_Test\Beez\ISO',
'S:\Test\Bob\Out_Test\Beez\ISO\Achat'
$Array | % {$_.TrimStart('S:\Test\Bob\Out_Test\')}

Can anyone help me out what the best way would be to trim of the beginning of the strings?

Upvotes: 3

Views: 8121

Answers (1)

ojk
ojk

Reputation: 2542

Try to use replace instead, like so:

$string = 'S:\Test\Bob\Out_Test\Beez\ISO\ISO\Environnement'
$string.Replace('S:\Test\Bob\Out_Test\','')

The reason why trimstart don't work is because it doesn work as you would expect. The input you give it, is not a string, but an array of characters.

You can read more about it here: http://msdn.microsoft.com/en-us/library/system.string.trimstart(v=vs.110).aspx

Upvotes: 3

Related Questions