Avatar of matedwards
matedwards
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Unexpected token $_ in Powershell command

I'm trying to bulk modify AD users UPN suffix with a Powershell script (below).

Import-Module ActiveDirectory
$oldSuffix = "canitpro.local"
$newSuffix = "rebeladmin.com"
$ou = "DC=canitpro,DC=local"
$server = "DCM1"
Get-ADUser -SearchBase $ou -filter * | ForEach-Object {
$newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
$_ | Set-ADUser -server $server -UserPrincipalName $newUpn
}

But I keep getting the error: Unexpected token '$_' in expression or statement

What is wrong with the $_ ?

I thought it represented every object in the pipeline?

Many thanks for any help
PowershellActive Directory

Avatar of undefined
Last Comment
oBdA

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
oBdA

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
matedwards

ASKER
Many thanks oBdA,

I'm trying to run it direct in the console.
I will cut and paste again from here and see.
Will update you soon.

Many thanks again
matedwards

ASKER
Thanks oBdA, worked a treat.

Being a newbie to powershell can I ask why I should use the -replace statement not the Replace() method?

Is it solely down to being case sensitive?

Many thanks again
oBdA

In this case because it's case insensitive.
As an alternative, you can make the string all lower before replacing, but that would include the part not to be replaced; that might not be what you want:
	$newUpn = $_.UserPrincipalName.ToLower().Replace($oldSuffix, $newSuffix)

Open in new window

Note that the -replace operator is actually way more powerful than the Replace() method - it uses a Regular Expression for the pattern to replace.
So don't go replacing the method with the operator all over the place before reading up on Regular Expressions.
To be completely correct, the "." in the name would need to be escaped with a backslash (or using [regex]::Escape()) since the "." means "any character" in RegEx, but in this case, it's rather safe to leave it in.
	$newUpn = $_.UserPrincipalName -replace ([regex]::Escape($oldSuffix)), $newSuffix

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23