PowerShell for Windows Admins

Aug 15 2018   4:04AM GMT

Splitting on a \

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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


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]

This also works

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

Keep it simple

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: