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

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 5 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

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

Post 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. :)
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

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

Post 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.
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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)
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
Attachments
OutlookSignatureFromTemplate.ps1
(1012 Bytes) Downloaded 149 times
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

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

Post by ITEngineer »

Mr. Vierra,

Yes, that does make sense.
Thanks for the sharing and the reply on this thread, I appreciate it muchly. :)
/* IT Engineer */
This topic is 5 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked