Link to home
Start Free TrialLog in
Avatar of matedwards
matedwardsFlag 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
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 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
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
Avatar of oBdA
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