Creating a Variable in a ForEach Loop to Use In Script

Hey All,
Trying to create something that updates the UPN & Email Address Fields in AD and sets the new primary SMTP address - all from a single value for the user.

Currently works fine if i import the value from the spreadsheet and specify the value as a variable, however i wanted to try and engineer this change without calling the value.

Currently have the below using “(”{0}@{1}" -f $user.samaccountname,“Test.com”)" to create the desired output but assume there is a better way via a variable and calling this into the CMDLets?

# Rename UPN and EmailAddress in AD & Set Primary SMTP Address #
foreach ($User in $Users) {
Set-ADUser -Identity $User.SamAccountName -UserPrincipalName ("{0}@{1}" -f $user.samaccountname,"Test.com") -EmailAddress ("{0}@{1}" -f $user.samaccountname,"Test.com") 
Set-RemoteMailbox -Identity ("{0}@{1}" -f $user.samaccountname,"Test.com") -PrimarySMTPAddress ("{0}@{1}" -f $user.samaccountname,"Test.com")
}

Appreciate any advice here.

If I understand correctly, put the variable and its string value before your Set-ADUser cmdlet like so.

foreach ($User in $Users) {
    $newaddress = "{0}@{1}" -f $user.samaccountname,"Test.com"
    Set-ADUser -Identity $User.SamAccountName -UserPrincipalName $newaddress -EmailAddress $newaddress 
    Set-RemoteMailbox -Identity $newaddress -PrimarySMTPAddress $newaddress
}
1 Like

Thank you very much - this is what i was looking for here and a simple change :slight_smile: