Dear experts,
I'm working on below script trying to replace the value of mailNickName with the prefix part of UPN value. It works great if we had EMPTY mailNickName field (where it showed <not set>). However, if there was value already existing in mailNickName field, in this example the value is test2 and the UPN prefix is test2.mcs
Cannot convert value "test2" to type "System.Int32". Error: "Input string was not in a correct format."
At D:\OneDrive - GTIIT\IT Dept\PowerShell\Scripts\Case_Study\Replace mailNickName with UPN prefix\test.ps1:9 char:26
+ if ($UPN_Prefix -ne -$_.mailNickname){
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
Below is the source code:
$OUs = "OU=Eaven-Testing,OU=Users,OU=XXX,DC=edu,DC=cn"
foreach ($OU in $OUs) {
Get-ADUser -Filter * -SearchBase $OU -Properties samAccountName, userPrincipalName, mailNickname, Enabled |
Where-Object { $_.Enabled -eq $True} |
ForEach-Object{
$parts = $_.userPrincipalName -split '@'
$UPN_Prefix = $parts[0]
if ($_.mailNickname){
if ($UPN_Prefix -ne -$_.mailNickname){
$was = $_.mailNickName
Set-ADUser -Identity $_.samAccountName -Replace @{mailNickname="$UPN_Prefix"}
}
else{
Write-host "$UPN_Prefix already exists, no change will be made on it."
}
}
else{
$was = "EMPTY"
Set-ADUser -Identity $_.samAccountName -Add @{mailNickname="$UPN_Prefix"}
}
[PSCustomObject]@{
Identity = $_.samAccountName
UPN = $_.userPrincipalName
NicknameWas = $was
NickNameNow = $parts[0]
}
} | Export-Csv -NoType 'C:\tmp\userPrincipalName_vs_mailNickname.csv'
}