Page 1 of 1

Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 8:04 am
by ITEngineer
Hi People,

I have the below PowerShell code to set the email signature in Outlook, but somehow there is one issue/bug that is still persisting.

Code: Select all

$templateFile = '\\domain.com\SYSVOL\domain.com\scripts\My Custom Signature.docx'
$templateFileNoMobile = '\\domain.com\SYSVOL\domain.com\scripts\My Custom Signature - No MobilePhone.docx'
$defaultTelephone = '555 12345'
$signatureName = 'My Custom Signature' ## Local signature name

Function Set-DocText($WordObject, $FindText, $ReplaceWith)
{
	$replaceAll = 2
	$findContinue = 1
	$matchCase = $false
	$matchWholeWord = $true
	$matchWildcards = $false
	$matchSoundsLike = $false
	$matchAllWordForms = $false
	$forward = $true
	$wrap = 1
	$format = $false
	[void]$WordObject.Selection.Find.Execute($FindText, $matchCase, $matchWholeWord, $matchWildcards, $matchSoundsLike, $matchAllWordForms, $forward, $wrap, $format, $ReplaceWith, $replaceAll)
}

#Get Active Directory information for current user
$sysInfo = New-Object -ComObject 'ADSystemInfo'
$userDN = $sysInfo.GetType().InvokeMember('UserName', 'GetProperty', $null, $sysInfo, $null)
$adUser = [ADSI]"LDAP://$($userDN)"
[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($sysInfo)

$signatureDir = "${ENV:AppData}\Microsoft\Signatures"
$signatureFile = "$($signatureDir)\$($signatureName).docx"
If (Test-Path -Path $signatureDir -PathType Leaf) { Remove-Item -Path $signatureDir -Force }
If (-not (Test-Path -Path $signatureDir)) { New-Item -Path $signatureDir -Itemtype Directory -Force | Out-Null }
Copy-Item -Path $(If ($ADUser.mobile) { $templateFile }
	Else { $templateFileNoMobile }) -Destination $signatureFile -Force

$msWord = New-Object -ComObject Word.Application
[void]$msWord.Documents.Open($signatureFile)

Set-DocText -WordObject $msWord -FindText 'AD_DisplayName' -ReplaceWith $ADUser.DisplayName.ToString()
Set-DocText -WordObject $msWord -FindText 'AD_Title' -ReplaceWith $ADUser.title.ToString()
Set-DocText -WordObject $msWord -FindText 'AD_Telephone' -ReplaceWith $(If ($ADUser.telephoneNumber) { $ADUser.telephoneNumber.ToString() }
	Else { $defaultTelephone })
If ($ADUser.mobile) { Set-DocText -WordObject $msWord -FindText 'AD_MobilePhone' -ReplaceWith $ADUser.mobile.ToString() }

# Save Signature files in multiple extensions (needed for Outlook)
$saveAs = @{
	'htm'  = 'wdFormatHTML'
	'rtf'  = 'wdFormatRTF'
	'txt'  = 'wdFormatText'
}
ForEach ($ext In $saveAs.Keys)
{
	$saveFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::($saveAs[$ext])
	$path = $signatureFile -replace 'docx$', $ext
	$msWord.ActiveDocument.SaveAs([ref]$path, [ref]$saveFormat)
}
$msWord.ActiveDocument.Close()

# Set signature as default
$emailOptions = $msWord.EmailOptions
$emailSignature = $emailOptions.EmailSignature
$emailSignatureEntries = $emailSignature.EmailSignatureEntries
$emailSignature.NewMessageSignature = $signatureName
$emailSignature.ReplyMessageSignature = $signatureName

$msWord.Quit()
[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($msWord)
The script above is working 99% except there is always EmailAccount name (in the format Firstname.LastName@domain.com) displayed in front of the AD_Display Name which ruins all of the email signatures.

This is the content of the MS_Word document:

Code: Select all

$ADDisplayName
$ADTitle
$ADTelephoneNumber
$ADMobilePhone
What I've done so far:

1. Recreate the MS Word .DOCX template manually, even without any display image - FAILED, the Firstname.LastName@domain.com is displayed.
2. Run the Set-EmailSignature.PS1 manually - WORKS perfectly fine, but this needs to be executed as Login Script.
3. Running it as Login Script User Configuration (Enabled) > Policies > Windows Settings > Scripts > Logon - FAILED, the Firstname.LastName@domain.com is displayed.

Any help would be greatly appreciated. :)

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 8:25 am
by jvierra
When posting large bits of code please post as an attached file.

I have given you the correct answer for this task twice now. Why do you keep going back to the old Office method that was never correct to begin with?

There is no need to create these files. They will be created automatically when you run this under a users account. You cannot just copy these files to a users folder as Outlook will not have the remaining information and the signatures will not work correctly.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 8:30 am
by ITEngineer
jvierra wrote:
Fri May 25, 2018 8:25 am
When posting large bits of code please post as an attached file.

I have given you the correct answer for this task twice now. Why do you keep going back to the old Office method that was never correct to begin with?
the attached method is working except that little annoying bit which display the email address in front of the AD_Displayname.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 8:34 am
by jvierra
Please attach your code as a file. It cannot be copied easily as posted and is not readable. This is a forum issue that has not been fixed at this point so please use a file.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 9:28 am
by jvierra
". Running it as Login Script User Configuration (Enabled) > Policies > Windows Settings > Scripts > Logon"

This code:

Code: Select all

# Set signature as default
$emailOptions = $msWord.EmailOptions
$emailSignature = $emailOptions.EmailSignature
$emailSignatureEntries = $emailSignature.EmailSignatureEntries
$emailSignature.NewMessageSignature = $signatureName
$emailSignature.ReplyMessageSignature = $signatureName
Creates the files that you are creating here:

Code: Select all

ForEach ($ext In $saveAs.Keys)
{
	$saveFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::($saveAs[$ext])
	$path = $signatureFile -replace 'docx$', $ext
	$msWord.ActiveDocument.SaveAs([ref]$path, [ref]$saveFormat)
}
There is no need to do this since the signature and files are created automatically.

Also you close the document before creating the signature. Only close the document at the end.

Remove this line:
$msWord.ActiveDocument.Close()

Place it just before the Quit().

The following is unnecessary as the script will end and remove the object:

[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($msWord)

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 9:30 am
by jvierra
ITEngineer wrote:
Fri May 25, 2018 8:04 am

The script above is working 99% except there is always EmailAccount name (in the format Firstname.LastName@domain.com) displayed in front of the AD_Display Name which ruins all of the email signatures.
If you used a template and bookmarks as I showed you before, you would not have this issue. The template can and should be placed on a network share. Provisions in the script should check to see if this has already been run and only rerun it if the template has changed.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 9:50 am
by jvierra
Part of your issue is that you are not using "dotx" files. You are using "DOTX" files which are not templates. You need to create a template with a DOTX extension.

You are also not using any template. Templates are loaded like this:
$doc = $msWord.Documents.Add($signatureTemplate)

Not like this:
[void]$msWord.Documents.Open($signatureFile)

We then use the $doc object to manage the document. "ActiveDocument" is normally used by Add-Ins to interact with the user. We are not running an Add-In but are assigning contents to a document with the help of a template.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Fri May 25, 2018 10:04 am
by jvierra
Here (attached) is a complete example of how to generate a signature and all files.

The issue that most users of this who have no Word training have is correctly creating the bookmarks. You must highlight the complete anchor text before defining it as a bookmark. The bookmark must then be given the name you want. All formatting of the anchor text must be done before highlighting and defining the bookmark.

Re: Need some help in debugging the PowerShell code to set email signature ?

Posted: Mon May 28, 2018 12:15 am
by ITEngineer
Mr. Vierra,

Yes, that does make sense.
Thanks for the sharing and the reply on this thread, I appreciate it muchly. :)