When you split texts, you typically lose the splitting character. That’s why the backslash in this example is lost:

 
PS> 'c:\test\file.txt' -split '\\'
c:
test
file.txt   
 

IMPORTANT: Note that the -split operator expects a regular expression. If you want to split at backslashes, since a backslash is a special character in regex, you need to escape it. The following call tells you what you need to escape: submit the literal text you want to use. The result is the escaped regex text:

 
PS> [regex]::Escape('\')
\\    
 

If you want to split without losing anything, you can use so-called look-aheads and look-behinds. This splits *after* a backslash (without removing it):

 
PS> 'c:\test\file.txt' -split '(?<=\\)'
c:\
test\
file.txt    
 

And this splits *before* each backslash:

 
PS> 'c:\test\file.txt' -split '(?=\\)'
c:
\test
\file.txt   
 




Twitter This Tip! ReTweet this Tip!

Anonymous