Public/Edit-UPN.ps1
Function Edit-UPN { <# .SYNOPSIS Edit current UPN .DESCRIPTION The default UPN is not always the one you want. This function allows you to change the UPN of one or more ActiveDirectory users. This function requires the ActiveDirectory module to function properly. .PARAMETER CurrentUPN Provide the current UPN .PARAMETER NewUPN Provide the new UPN .Parameter AuthType Specifies the authentication method to use. Possible values for this parameter include: Negotiate or 0 Basic or 1 The default authentication method is Negotiate. A Secure Sockets Layer (SSL) connection is required for the Basic authentication method. The following example shows how to set this parameter to Basic. -AuthType Basic .Parameter Credential Specifies the user account credentials to use to perform this task. The default credentials are the credentials of the currently logged on user unless the cmdlet is run from an Active Directory PowerShell provider drive. If the cmdlet is run from such a provider drive, the account associated with the drive is the default. To specify this parameter, you can type a user name, such as "User1" or "Domain01\User01" or you can specify a PSCredential object. If you specify a user name for this parameter, the cmdlet prompts for a password. You can also create a PSCredential object by using a script or by using the Get-Credential cmdlet. You can then set the Credential parameter to the PSCredential object The following example shows how to create credentials. $AdminCredentials = Get-Credential "Domain01\User01" The following shows how to set the Credential parameter to these credentials. -Credential $AdminCredentials If the acting credentials do not have directory-level permission to perform the task, Active Directory PowerShell returns a terminating error. .Parameter Identity Specifies an Active Directory user object by providing one of the following property values. The identifier in parentheses is the LDAP display name for the attribute. Distinguished Name Example: CN=SaraDavis,CN=Europe,CN=Users,DC=corp,DC=contoso,DC=com GUID (objectGUID) Example: 599c3d2e-f72d-4d20-8a88-030d99495f20 Security Identifier (objectSid) Example: S-1-5-21-3165297888-301567370-576410423-1103 SAM account name (sAMAccountName) Example: saradavis The cmdlet searches the default naming context or partition to find the object. If two or more objects are found, the cmdlet returns a non-terminating error. This parameter can also get this object through the pipeline or you can set this parameter to an object instance. This example shows how to set the parameter to a distinguished name. -Identity "CN=SaraDavis,CN=Europe,CN=Users,DC=corp,DC=contoso,DC=com" This example shows how to set this parameter to a user object instance named "userInstance". -Identity $userInstance .Parameter ResultPageSize Specifies the number of objects to include in one page for an Active Directory Domain Services query. The default is 256 objects per page. The following example shows how to set this parameter. -ResultPageSize 500 .Parameter ResultSetSize Specifies the maximum number of objects to return for an Active Directory Domain Services query. If you want to receive all of the objects, set this parameter to $null (null value). You can use Ctrl+c to stop the query and return of objects. The default is $null. The following example shows how to set this parameter so that you receive all of the returned objects. -ResultSetSize $null .Parameter SearchBase Specifies an Active Directory path to search under. When you run a cmdlet from an Active Directory provider drive, the default value of this parameter is the current path of the drive. When you run a cmdlet outside of an Active Directory provider drive against an AD DS target, the default value of this parameter is the default naming context of the target domain. When you run a cmdlet outside of an Active Directory provider drive against an AD LDS target, the default value is the default naming context of the target LDS instance if one has been specified by setting the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance. If no default naming context has been specified for the target AD LDS instance, then this parameter has no default value. The following example shows how to set this parameter to search under an OU. -SearchBase "ou=mfg,dc=noam,dc=corp,dc=contoso,dc=com" When the value of the SearchBase parameter is set to an empty string and you are connected to a GC port, all partitions will be searched. If the value of the SearchBase parameter is set to an empty string and you are not connected to a GC port, an error will be thrown. The following example shows how to set this parameter to an empty string. -SearchBase "" .Parameter SearchScope Specifies the scope of an Active Directory search. Possible values for this parameter are: Base or 0 OneLevel or 1 Subtree or 2 A Base query searches only the current path or object. A OneLevel query searches the immediate children of that path or object. A Subtree query searches the current path or object and all children of that path or object. The following example shows how to set this parameter to a subtree search. -SearchScope Subtree .Parameter Server Specifies the Active Directory Domain Services instance to connect to, by providing one of the following values for a corresponding domain name or directory server. The service may be any of the following: Active Directory Lightweight Domain Services, Active Directory Domain Services or Active Directory Snapshot instance. Domain name values: Fully qualified domain name Examples: corp.contoso.com NetBIOS name Example: CORP Directory server values: Fully qualified directory server name Example: corp-DC12.corp.contoso.com NetBIOS name Example: corp-DC12 Fully qualified directory server name and port Example: corp-DC12.corp.contoso.com:3268 The default value for the Server parameter is determined by one of the following methods in the order that they are listed: -By using Server value from objects passed through the pipeline. -By using the server information associated with the Active Directory PowerShell provider drive, when running under that drive. -By using the domain of the computer running Powershell. The following example shows how to specify a full qualified domain name as the parameter value. -Server "corp.contoso.com" .EXAMPLE PS C:\> Edit-UPN -CurrentUPN "Fabrikam.com" -NewUPN "Contoso.com" -SearchBase "OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM" This example changes the Current UPN 'Fabrikam.com' to 'Contoso.com' and uses the SearchBase 'OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM' as the location for the accounts with the UPN 'Fabrikam.com' .LINK Get-ADUser .LINK Set-ADUser .LINK about_Functions_Advanced .LINK about_CommonParameters #> [CmdletBinding( DefaultParameterSetName = 'Filter', ConfirmImpact = 'Medium', HelpURI = 'https://cstekelenburg.visualstudio.com/JBOSCollection/_wiki/wikis/JBOADS?pagePathEdit-UPN' )] [OutPutType('Microsoft.ActiveDirectory.Management.ADUser[]')] Param ( [Parameter( ParameterSetName = 'Identity', Mandatory = $true, ValueFromPipeline = $true, Position = 0 )] [AllowNull()] [Microsoft.ActiveDirectory.Management.ADUser]$Identity, [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [ValidateSet("Basic", "1", "Negotiate", "0")] [Microsoft.ActiveDirectory.Management.ADAuthType]$AuthType = "Negotiate", [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [PSCredential][System.Management.Automation.Credential()]$Credential, [Parameter( ParameterSetName = 'Filter', Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Provide the current UPN' )] [Parameter(ParameterSetName = 'Identity')] [ValidateNotNullOrEmpty()] [string]$CurrentUPN, [Parameter( ParameterSetName = 'Filter', Mandatory = $true, ValueFromPipeline = $true, HelpMessage = 'Provide the new UPN' )] [Parameter(ParameterSetName = 'Identity')] [ValidateNotNullOrEmpty()] [string]$NewUPN, [Parameter( ParameterSetName = 'Filter', ValueFromPipeline = $true, HelpMessage = 'Provide the SearchBase' )] [Parameter(ParameterSetName = 'Identity')] [string]$SearchBase, [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [int]$ResultPageSize = 256, [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [int]$ResultSetSize = $null, [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [ValidateSet('Base', 'OneLevel', 'Subtree')] [Microsoft.ActiveDirectory.Management.ADSearchScope]$SearchScope = "Subtree", [Parameter(ParameterSetName = 'Filter')] [Parameter(ParameterSetName = 'Identity')] [string]$Server ) Begin { If (-not $PSBoundParameters.ContainsKey('Debug')) { $DebugPreference = $PSCmdlet.SessionState.PSVariable.GetValue('DebugPreference') } If (-not $PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference') } If (-not $PSBoundParameters.ContainsKey('WhatIf')) { $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference') } If (-not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference') } If (-not $PSBoundParameters.ContainsKey('ErrorAction')) { $ErrorActionPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ErrorActionPreference') } If (-not $PSBoundParameters.ContainsKey('WarningAction')) { $WarningPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WarningPreference') } If (-not $PSBoundParameters.ContainsKey('InformationAction')) { $WarningPreference = $PSCmdlet.SessionState.PSVariable.GetValue('InformationPreference') } Write-Debug ('({0}) PsBoundParameters:' -f $MyInvocation.MyCommand) $PSBoundParameters.GetEnumerator() | ForEach-Object { Write-Debug ('({0}) {1}' -f $MyInvocation.MyCommand, $_ ) } Write-Debug ('({0}) DebugPreference: {1}' -f $MyInvocation.MyCommand, $DebugPreference) Write-Debug ('({0}) ParameterSetName: {1}' -f $MyInvocation.MyCommand, $($PSCmdlet.ParameterSetName)) Write-Verbose ('{0}:: Function started' -f $MyInvocation.MyCommand) Write-Verbose ( '{0}:: Confirm={1} ConfirmPreference={2} WhatIf={3} WhatIfPreference={4} ErrorAction={5} ErrorActionPreference={6} WarningAction={7} WarningPreference={8} InformationAction={9} InformationPreference={10}' ` -f $MyInvocation.MyCommand, $Confirm, $ConfirmPreference, $WhatIf, $WhatIfPreference, $ErrorAction, $ErrorActionPreference, $WarningAction, $WarningPreference, $InformationAction, $InformationPreference ) $CurUPN = "*@" $CurUPN += $CurrentUPN If ($PSBoundParameters.ContainsKey('CurrentUPN')) { Write-Debug "CurrentUPN: $($PSBoundParameters['CurrentUPN'])" } If ($PSBoundParameters.ContainsKey('SearchBase')) { Write-Debug "Searchbase: $($PSBoundParameters['SearchBase'])" } } Process { Try { If ($PSBoundParameters.ContainsKey('SearchBase')) { $SBText = " using searchbase: {0}" -f $SearchBase } Else { $SBText = "" } Write-Verbose ("$($MyInvocation.MyCommand.Name):: Retrieving users with UPN {0} from ActiveDirectory{1}" -f $CurUPN, $SBText) $GetADUserParams = @{ "AuthType" = $AuthType "SearchScope" = $SearchScope "ResultPageSize" = $ResultPageSize } If ($PSBoundParameters.ContainsKey('Credential')) { $GetADUserParams.Credential = $PSBoundParameters['Credential'] } If ($PSBoundParameters.ContainsKey('CurrentUPN')) { $GetADUserParams.Filter = "{ UserPrincipalName -like $CurUPN }" } If ($PSBoundParameters.ContainsKey('Identity')) { $GetADUserParams.Identity = $PSBoundParameters['Identity'] } If ($PSBoundParameters.ContainsKey('SearchBase')) { $GetADUserParams.SearchBase = $PSBoundParameters['SearchBase'] } If ($PSBoundParameters.ContainsKey('Server')) { $GetADUserParams.Server = $PSBoundParameters['Server'] } $Users = Get-ADUser @GetADUserParams Write-Debug "NewUPN: $NewUPN" $Users | ForEach-Object { Write-Verbose ("$($MyInvocation.MyCommand.Name):: Setting UPN for {1}" -f $_) $UPN = $_.UserPrincipalName.Replace("$CurrentUPN", "$NewUPN") $SetADUserParams = @{ UserPrincipalName = $UPN } If ($PSBoundParameters.ContainsKey('Credential')) { $SetADUserParams.Credential = $PSBoundParameters['Credential'] } If ($PSBoundParameters.ContainsKey('Identity')) { $SetADUserParams.Identity = $PSBoundParameters['Identity'] } If ($PSBoundParameters.ContainsKey('SearchBase')) { $SetADUserParams.SearchBase = $PSBoundParameters['SearchBase'] } If ($PSBoundParameters.ContainsKey('Server')) { $SetADUserParams.Server = $PSBoundParameters['Server'] } Set-ADUser @SetADUserParams } } Catch [System.Management.Automation.RuntimeException] { Write-Warning "No users found! Are you connected to the ActiveDirectory?" $Error[0] } Catch [Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Warning "ActiveDirectory Module loaded but no Domain Controller found!" $Error[0] } Catch { $Error[0] } } End { Write-Verbose "$($MyInvocation.MyCommand.Name):: Cleaning up" Remove-Variable CurUPN, Users, UPN, CurrentUPN, NewUPN -ErrorAction SilentlyContinue If ($PSBoundParameters['Debug']) { $DebugPreference = 'SilentlyContinue' } Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended" } } Set-Alias -Name Update-UPN -Value Edit-UPN -Description "Edit UPN" -Option ReadOnly -PassThru -ErrorAction SilentlyContinue |