Script Repository


Save user account properties to a Microsoft Word document

February 18, 2021
2238

The script can be used in business rules, custom commands and scheduled tasks to save property values of a user account to a Microsoft Word document. For example, the script can be used to automatically create documents with information on new users once they are created in AD. For this purpose, you need to create a business rule that will run the script after creating a new user. For more details, see Run PowerShell Script after Creating a User.

Prerequisites:

To be able to create a document containing user data, first, you need to create a Microsoft Word Template (DOTX) that will be used for creating the documents. In the template, add placeholders (portions of texts) that will be replaced with the actual values of user properties.

Parameters:

  • $templatePath - Specifies a path to the template that will be used for creating documents.
  • $filePath - Specifies a path to a document that will be created by the script.
    You can use value references in both the template and the document paths. When the script will be executed, the value references will be replaced with property values of the user on which it is executed. For example, if you specify C:\reports\%fullname%.docx, and the script is executed on user John Doe, the path will be C:\reports\John Doe.docx.
  • $propertyMap - Specifies a map of text placeholders and the corresponding value references for the properties to substitute placeholders with. Format:

    "Placeholder" = "%value reference%"

    For example, if you specify the following "FullName" = "%fullname%", the script will find text FullName in the template and replace it with the full name of the user on which it is executed.

Known Issues:

When run programmatically, Word does not have a user profile loaded. This prevents Word from loading any templates. A typical behavior is that you get the following error when trying to run the script: Word was unable to read this document. It may be corrupt.

Resolution

Create the following folder: C:\Windows\SysWOW64\config\systemprofile\Desktop, where C:\Windows is the folder where Windows is installed.

Edit Remove
PowerShell
# File paths
$templatePath = "C:\templates\template.dotx" # TODO: modify me
$filePath = "C:\reports\%fullname%.docx" # TODO: modify me

# User properties to include in the document
$propertyMap = @{
    "FullName" = "%fullname%";
    "Username" = "%username%";
    "Mail" = "%mail%";
    "Alias" = "%mailNickname%";
    "Password" = "%unicodePwd%"
} # TODO: modify me

# Function to replace text in a Word document
function Replace($findText, $replaceText, $selection)
{
    # Search parameters
    $replaceAll = 2
    $findContinue = 1
    $matchCase = $False
    $matchWholeWord = $True 
    $matchWildcards = $False 
    $matchSoundsLike = $False 
    $matchAllWordForms = $False
    $forward = $True
    $wrap = $FindContinue
    $format = $False
    
    # Perform replacement
    $selection.Find.Execute(
    $findText,
    $matchCase,
    $matchWholeWord,
    $matchWildcards,
    $matchSoundsLike,
    $matchAllWordForms,
    $forward,
    $wrap,
    $format,
    $replaceText,
    $replaceAll
    )
}

function ReleaseComObjects($object)
{
    [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($object)
}

try
{
    # Start Microsoft Word
    try
    {
        $objWord = New-Object -ComObject Word.Application
    }
    catch
    {
        $Context.LogMessage("Cannot start Microsoft Word. " + $_.Exception.Message, "Warning")
        return
    }
    
    $objWord.Visible = $False
    $objWord.DisplayAlerts = 0

    # Open template
    $missing = [System.Reflection.Missing]::Value
    $document = $objWord.Documents.Add($templatePath)
    $selection = $objWord.Selection
    
    # Replace placeholders with actual user data
    foreach ($findText in $propertyMap.Keys)
    {
        Replace $findText $propertyMap[$findText] $selection
    }
    
    # Save as a new document
    $document.SaveAs([ref]$filePath)
}
finally
{
    # Close Microsoft Word
    ReleaseComObjects $selection
    [ref]$saveOption = "Microsoft.Office.Interop.Word.WdSaveOptions" -as [type]
    $document.Close([ref]$saveOption::wdDoNotSaveChanges)
    ReleaseComObjects $document
    $objWord.quit()
    ReleaseComObjects $objWord
}


Comments ( 4 )
avatar
Romildo Wildgrube
May 22, 2018
If you run into weird problems with the script and error messages that looks like code error like
"Exception calling "FinalReleaseComObject" with "1" argumetn(s): "Value cannot be null. Parameter name: o"

Check the following article and that should fix your problem
http://timwappat.info/post/2013/09/03/Solution-to-Excel-Automation-VBNETC-error-running-as-a-service-0x800A03EC-MicrosoftOfficeInteropExcelWorkbooksOpen
avatar
Support
May 22, 2018
Thank you for providing the article. Still we should mention, that unfortunately, there is never a guarantee that any of the solutions described in it will actually work.
avatar
Tony
Jul 08, 2020
This process had been working correctly for some time. We now have moved the powershell side to a custom command to have one location of all changes. In doing this the value that should be captured for Password is not saving to the word document. We have a property pattern applied to the top level OU that should be auto creating the password.
avatar
Support
Jul 09, 2020

Hello Tony,

 

The thing is that value reference %unicodePwd% can only be used in Business Rules triggering Before/After creating a user, resetting/changing/self-resetting password of a user. In all other cases, including Custom Commands, the value reference will resolve into an empty value.
You can execute the Custom Command in your Business Rule and pass the password as a parameter value. In this case, the action in the Business Rule will look like the following, where userPassword is the parameter name:

Execute 'My Command' for the user (userPassword: '%unicodePwd%')


For information on how to use parameters in Custom Commands, have a look at the following tutorial: https://www.adaxes.com/tutorials_ActiveDirectoryManagement_CreateCustomCommand.htm#how_to_use_parameters.

Leave a comment