In PowerShell, how can I exclude a specific string from string?

SAM2009
SAM2009 used Ask the Experts™
on
Hi,

In PowerShell, how can I exclude a specific string from string?

Like:

$user= ”domain\user01”

I want to remove “domain\”

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
A simple Split() will do:
$user.Split('\')[1]

Open in new window

Sam JacobsDirector of Technology Development, IPM

Commented:
$user -replace "domain" ""
Sam JacobsDirector of Technology Development, IPM
Commented:
Actually, that would be $user.replace("domain\","")
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
With the replace operator (which expects a RegEx), it would need to be (note the comma and the escaped backslash)
$user -replace "domain\\", ""

Open in new window

Careful with the string Replace() method, though: unlike the -replace operator, it is cAsE sEnSiTiVe.
PS C:\> $user = "Domain\user01"
PS C:\> $user.Replace('domain\', '')
Domain\user01

PS C:\> $user -replace "Domain\\", ""
user01

Open in new window

Sam JacobsDirector of Technology Development, IPM

Commented:
Thanks, oBdA! I wasn't aware of the case sensitivity.

Author

Commented:
Why using double backslash?:\\
Sam JacobsDirector of Technology Development, IPM

Commented:
You need to escape the first backslash - it has a special meaning to a regular expression, which is what is expected by the replace operator.

Author

Commented:
Ok thanks.

If I need to remove everything before \, what is the good syntax?

Author

Commented:
Like this ?:

replace ("^\w*\\","")
Sam JacobsDirector of Technology Development, IPM
Commented:
The replace operator expects a RegEx - not the replace method, which is what you have above.
I would stick to oBdA's Split() method.
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Everything before, or including the backslash?
I'd still use the Split():
$user.Split('\')[1]

Open in new window

As RegEx, I'd use a .* with a non-greedy quantifier (btw, if you're replacing with nothing, you can omit the second operand):
$user -replace ".*?\\"

Open in new window

Author

Commented:
Hey thanks guy for your help again!:-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial