header image

Splitting on a \

Posted by: | August 15, 2018 Comments Off on Splitting on a \ |

Splitting strings is usually easy – you use the –split operator or the Split() method. Occasionally you may hit a problem – for instance splitting on a \ character.

Let me demonstrate with an example.

PS> Get-CimInstance -ClassName Win32_ComputerSystem | select Username

Username
——–
W510W10\Richard

 

I get the domain (in this case the machine as its a local account) and the user name. What I want is just the user name.

PS> (Get-CimInstance -ClassName Win32_ComputerSystem | select -ExpandProperty Username) -split ‘\’
parsing “\” – Illegal \ at end of pattern.
At line:1 char:1
+ (Get-CimInstance -ClassName Win32_ComputerSystem | select -ExpandProp …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException

 

I’ve seen possible solutions like this

(Get-CimInstance -ClassName Win32_ComputerSystem | select username | out-string).split(‘\’)

 

But Out-String isn’t necessary in this case.

The problem is that \ is the PowerShell escape character so you have to escape it so that its treated as a literal character

PS> ((Get-CimInstance -ClassName Win32_ComputerSystem | select -ExpandProperty Username) -split ‘\\’)[1]
Richard

 

This also works

PS> (Get-CimInstance -ClassName Win32_ComputerSystem | select -ExpandProperty Username).Split(‘\’)[1]
Richard

 

Keep it simple

under: PowerShell

Comments are closed.

Categories