Search code examples
powershellspecial-characterssignampersand

Escaping ampersand (&) and plus sign (+) in Powershell


I am trying to perform a Set-ADUsercommand to Active Directory in order to update the mobile and title attribute as below :

Set-ADUser -Identity "UID1234" -Mobile "+2345678" -Server \$domainController[0] -Credential $mycred;

This command goes through. Unfortunately, the plus sign (+) is being replaced by a space in the account.

I also want to perform the same command to update the title attribute :

Set-ADUser -Identity "UID1234" -Title "Employee & Manager" -Server \$domainController[0] -Credential $mycred;

Here, I am getting the following error : The string is missing the terminator \" because of the ampersand (&) character that is not understood as a proper character as it is generally used for calling variables.

For both of these cases, I understand that there should be a way to escape these characters but I was not successful by using escapers such as backslash () or back-single quote (`).

Any help would be very appreciated !


Solution

  • I have two suggestions. First, try using a single quote around the text as opposed to double quotes. PowerShell will treat any text between single quotes as literal.

    Example:

    $i = 10
    Write-Host 'The value of i is $i'
    > The value of i is $i
    

    Secondly,

    If you wish to leave the double quotes, which you will have to do for this to work, place a ` (Backtick/grave accent character) before the "&" and "+" signs.

    "`+2345678"
    "Employee `& Manager"