Design A Simple and Reusable Word Document Template Using PScribo Part 2

This is the second part to my post on designing a document template using PScribo.

Goals:

  • Using the approach from part one, create a minimally reusable solution.

Required PowerShell Modules:

  • I tested this using latest Windows PowerShell 5.1
  • PScribo

Required CSV File:

Complete Script:

<#
	.SYNOPSIS
	Create an $Team Architecture Starter Word Document
	.DESCRIPTION
	Creates a Word document with the default $Team architecture sections. Requires module PScribo. Can be used to output the document in HTML as well.
	.PARAMETER Format
	A string array that defines the format of the output.
	.PARAMETER Path
	The folder to store the output file under.
	.PARAMETER FileName
	The filename of the output file.
	.PARAMETER Title
	The string that will appear on the title page.
	.PARAMETER SectionDictCsv
	The full path to the section CSV file used to build the section hash table.
	.PARAMETER Company
    The company the document is created for
    .PARAMETER Team
    The team the document is created for
	A description of the PassThru parameter.
	.EXAMPLE
	PS C:\> .\SolutionStarterV1.ps1 -Company $yourCompany -Team $YourTeam
	.Inputs
    SectionDict Csv file. To provide a simple method of documenting all standard topics used by the team and provide a way 
	for selecting among optional sections.The CSV file has the following column headers:
	Section: Document the ordering and relationships for the topics, 1, 2, 2.1, etc.
	Key: The Section Name, 'Document Control, Overview, etc.
	Value: Indicate if a section should be included or not. Blank for no, 'x' for yes.
	Comments: Any text
    cover_image.txt - The image used on the coversheet.
    .Outputs
    By default the script outputs both MS Word docx and an HTML file. 
	.NOTES
    PScribo Sections can be nested. The general approach in the script is to nest a section inside its parent section like so,
	Section 1 { Section 1.2 {} } Section 2{...}. Then wrap the sections in if statements.
	This allows for selection of individual sub sections and entire parent sections.
	If the value of the key in the sections hash table is null then it evaluates to false in the if statement.
    If a top level section is deselected, all it's subsections are automaticly deselected in the script.
    .LINK
    https://www.powershellgallery.com/packages/PScribo/0.9.1
#>
[CmdletBinding()]
param
(
    [Parameter(Mandatory = $false)]
    [System.String[]]$Format = @('Html', 'Word'),
    [Parameter(Mandatory = $false)]
    [System.String]$Path = "$env:OneDrive\Projects\Samples\Documentation\Solutions\",
    [Parameter(Mandatory = $false)]
    [System.String]$FileName = "SolutionStarterSample",
    [Parameter(Mandatory = $false)]
    [System.String]$Project = "Samples",
    [Parameter(Mandatory = $True)]
    [System.String]$Company,
    [Parameter(Mandatory = $True)]
    [System.String]$Team = "Your Team",
    [Parameter(Mandatory = $True)]
    [System.String]$userName,
    [Parameter(Mandatory = $True)]
    [System.String]$userEmail,
    [Parameter(Mandatory = $false)]
    [System.String]$Title = "Solution Starter Document Sample",
    [Parameter(Mandatory = $false)]
    [System.String]$SectionDictCsv = ".\SectionDict.csv",
    [System.Management.Automation.SwitchParameter]$PassThru

)
#Region Module Import
try {
    Import-Module PScribo -Force -Verbose:$false
}
Catch {
    Write-Host "This Script Requires PScribo. It can be installed from the PowerShell Gallery."
}
# End Module Import
# Region Functions
function Get-SelectionFromUser {
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$Options,
        [Parameter(Mandatory = $true)]
        [string]$Prompt
    )
	
    [int]$Response = 0;
    [bool]$ValidResponse = $false
	
    while (!($ValidResponse)) {
        [int]$OptionNo = 0
        Write-Host $Prompt -ForegroundColor 'GREEN'
        foreach ($Option in $Options) {
            $OptionNo += 1
            Write-Host ("[$OptionNo]: {0}" -f $Option)
        }
        if ([Int]::TryParse((Read-Host), [ref]$Response)) {
            if ($Response -eq 0) {
                return ''
            }
            elseif ($Response -le $OptionNo) {
                $ValidResponse = $true
            }
        }
    }
	
    return $Options.Get($Response - 1)
}
function get-SectionDict {
    $SectionDict = @{}
    if (Test-Path -Path $SectionDictCsv) {
        $cdText = Import-Csv $SectionDictCsv
        $cdText | ForEach-Object { if ($_.Key -ne '#') { $SectionDict.add("$($_.key)", "$($_.value)") } }
    }
    else {
        Write-Host "$SectionDictCsv not found - Exiting"
        exit
    }
    Return $SectionDict
}
#End Functions

#Region Data Gathering
$sections = Get-SectionDict
$currentDate = Get-Date -Format "M/dd/yyyy"
$path = $path.Replace('Samples', $project)
# Does not overwrite if $path exists
Write-Host "Creating folder $path if it does not exist"
New-Item -Path $path -ItemType Directory -Force | Out-Null
$fullpath = $path + $FileName
#For dynamic table example
$services = Get-CimInstance -ClassName Win32_Service | Select-Object -Property DisplayName, State, StartMode | Sort-Object -Property DisplayName
# end Data Gathering
$selection = Get-SelectionFromUser -Prompt "Do you want to create/overwrite $fullpath documents?" -Options 'Yes', 'No'
If ($selection -eq "No") {
    Write-Host "Exiting Script" -ForegroundColor 'RED'
    Exit
}
else {
    Write-Host "Continuing" -ForegroundColor 'GREEN'
}
# region Tables
$owner = "$Team"
$dataClass = "$Company Internal Use"
$docControlTable = [PSCustomObject] [ordered]@{
    'Author'              = $userName;
    'Document Owner'      = "$owner";
    'Document Name'       = $Title;
    'File Name'           = $FileName
    'Data Classification' = "$dataclass";
    'Dated'               = $currentDate;
    'Version'             = "0.0"
}
$versionTable = @(
    [ordered]@{'Change Author' = $userName; 'Date' = $currentDate; 'Change or Event' = "File created" }
    [ordered]@{'Change Author' = ''; 'Date' = ''; 'Change or Event' = "" }
    [ordered]@{'Change Author' = ''; 'Date' = ''; 'Change or Event' = "" }
)
$contibutorsTable = @(
    [ordered]@{'Contributor' = $userName; 'Role' = 'Author'; 'Email' = $userEmail }
    [ordered]@{'Contributor' = ''; 'Role' = ''; 'Email' = '' }
    [ordered]@{'Contributor' = ''; 'Role' = ''; 'Email' = '' }
)
$distributionTable = @(
    [ordered]@{'Name' = $userName; 'Responsibility'	= 'Author'; 'Email' = $userEmail }
    [ordered]@{'Name' = ''; 'Responsibility'	= ''; 'Email' = '' }
    [ordered]@{'Name' = ''; 'Responsibility'	= ''; 'Email' = '' }
)
$osTable = @(
    [ordered]@{"OS Name" = ''; "OS Version" = ''; "Node Count" = '' }
    [ordered]@{"OS Name" = ''; "OS Version" = ''; "Node Count" = '' }
    [ordered]@{"OS Name" = ''; "OS Version" = ''; "Node Count" = '' }
)
$portTable = @(
    [ordered]@{"Source" = ''; "Source Port" = ''; "Destination Port" = ''; "Protocol" = '' }
    [ordered]@{"Source" = ''; "Source Port" = ''; "Destination Port" = ''; "Protocol" = '' }
    [ordered]@{"Source" = ''; "Source Port" = ''; "Destination Port" = ''; "Protocol" = '' }
)
$softwareTable = [PSCustomObject] [ordered]@{
    'Software Vendor'        = '';
    'Software Name'          = '';
    'Target Install Version' = '';
    'Description'            = ''
}
$hardwareTable = [PSCustomObject] [ordered]@{
    'Hostname'            = '';
    'Physical or Virtual' = '';
    'Operating System'    = '';
    'Function'            = '';
    'CPU Count'           = '';
    'Clustering'          = '';
    'Core Count'          = '';
    'Memory'              = '';
    'Network Interfaces'  = '';
    'Data Center'         = '';
    'Storage'             = '';
    'Backup'              = ''
}
$raciTable = @(
    [ordered]@{"Function" = 'Day to day operation'; "Responsible" = "$Team Operations"; "Accountable" = "$Team operations"; "Consulted" = "$Team Architecture"; "Informed" = "$Team management" }
    [ordered]@{"Function" = ''; "Responsible" = ''; "Accountable" = ''; "Consulted" = ''; "Informed" = "" }
    [ordered]@{"Function" = ''; "Responsible" = ''; "Accountable" = ''; "Consulted" = ''; "Informed" = "" }
    [ordered]@{"Function" = ''; "Responsible" = ''; "Accountable" = ''; "Consulted" = ''; "Informed" = "" }
)
$vendorTable = @(
    [ordered]@{"Vendor" = ''; "Support Contract" = ''; "Support Type" = ''; "Support Web Page" = '' }
    [ordered]@{"Vendor" = ''; "Support Contract" = ''; "Support Type" = ''; "Support Web Page" = '' }
    [ordered]@{"Vendor" = ''; "Support Contract" = ''; "Support Type" = ''; "Support Web Page" = '' }
)
# End region tables
#$cover_image = [System.Convert]::ToBase64String((Get-Content -Path .\cover.png -Encoding Byte))
$ThisDocument = Document -Name $filename {
    #region Styles
    Style -Name Normal -Size 12 -Font Arial -Color 'Black'
    Style -Name 'TableNormal' -Size 10 -Font Arial -Color 'Black'
    Style -Name 'TableHeaderNormal' -Size 10 -Font Arial -Color 'Black' -Bold
    Style -Name TitleLine1 -Align Center -Size 36 -Bold -Color 'MediumVioletRed' -Font Arial
    Style -Name TitleDate -Align Center -Size 14 -Font Arial
    Style -Name TitleAuthor -Align Center -Size 16 -Bold -Font Arial
    Style -Name 'Heading 1' -Size 16 -Align Left -Bold -Underline -Font Arial -Color 'CadetBlue'
    Style -Name 'Heading 2' -Size 14 -Align Left -Font Arial -Color 'Black' -Bold
    Style -Name 'Heading 3' -Size 12 -Align Left -Font Arial -Color 'Black' -Bold
    Style -Name 'NotHeading 1' -Size 16 -Align Left -Bold -Underline -Font Arial -Color 'CadetBlue'
    Style -Name 'Stopped Service' -Color White -BackgroundColor Firebrick -Bold
    TableStyle  'Borderless' -HeaderStyle TableNormal -RowStyle TableNormal
    TableStyle -Name 'ListGrid' -HeaderStyle TableHeaderNormal -RowStyle TableNormal -BorderWidth 2
    Style -Name RightAligned -Align Right -Size 10 -Font Arial
    Style -Name footer -Align Center -Size 10 -Font Arial
    #end region Styles
    $CoverImage = Get-Content -Path .\cover_image.txt
    DocumentOption -ForceUppercaseSection -EnableSectionNumbering -PageSize Letter -MarginTopAndBottom 36 -MarginLeftAndRight 54
    Blankline -Count 2
    Paragraph "$Title" -Style TitleLine1
    BlankLine -Count 2
    Image -Text "#Company" -Align Center -Base64 $CoverImage
    BlankLine -Count 1
    Paragraph "$userName, $Team" -Style TitleAuthor
    Paragraph "$userEmail" -Style TitleDate
    BlankLine -Count 1
    Paragraph "Date:$currentDate" -Style TitleDate
    PageBreak
    Paragraph "All rights reserved. $Company is trademark of $Company Corporation in the United States and/or other countries. Other company trademarks are also acknowledged." -Size 10 -Italic
    PageBreak
    Section "Document Control" -Style 'NotHeading1' -ExcludeFromTOC -ScriptBlock {
        Paragraph "Document Distribution and Review" -Bold
        Paragraph "This document is for internal use by the $Company $Team. It may be shared with other $Company organizations on an as needed basis."
        Paragraph "The author will distribute this document to the Change Reviewers and Approvers when first published and as updates are made. You may obtain the latest version of this document by email request to the author."
        BlankLine -Count 1
        Table -Object $docControlTable -List -Style listGrid -ColumnWidths 25, 75
        Paragraph "Contributors" -Bold
        Table -Object $contibutorsTable -Style listGrid
        Paragraph "Distribution List" -Bold
        Table -Object $distributionTable -Style listGrid
        Paragraph "Event and Change History" -Bold
        Table -Object $versionTable -Style listGrid
    }	
    PageBreak
    TOC -Name "Table of Contents"
    if ($sections.'OverView') {
        PageBreak
        Section -Name "Overview" -Style 'Heading1' -ScriptBlock {
            Paragraph "Short paragraph describing the project here. Include information on the project sponsor and any team strategic work streams related to this project."
            if ($sections.'Goals and Objectives') {
                Section -Name "Goals and Objectives" -Style 'Heading2' {
                    Paragraph "A high-level description of the purpose of this solution. Include target completion date if known."
                }
            }
            if ($sections.'Services Description') {
                Section -Name "Services Description" -Style 'Heading2' -ScriptBlock {
                    Paragraph "What does the project implement? Avoid use of product names and instead describe the functional aspects of the implemented solution."
                }
            }
            if ($sections.'Definitions') {
                Section "Definitions" -Style 'Heading2' {
                    Paragraph "Define technical terms and acronyms that the intended audience may not understand"
                }
            }
            if ($sections.'Scope') {
                Section -Name "Scope" -Style 'Heading2' -ScriptBlock {
                    Paragraph "Describe the scope of the project. Which $Team environments does the implemented solution impact? Who are the intended end users?"
                }
            }
        }
    }
    if ($sections.'Dependencies and Constraints') {
        PageBreak
        Section -Name "Dependencies and Constraints" -Style 'Heading1' -ScriptBlock {
            Paragraph "Dependencies:" -Bold
            Paragraph "TBD"
            Blankline -Count 1
            Paragraph "Constraints:" -Bold
            Paragraph "TBD"
        }
    }
    if ($sections.'Naming Conventions') {
        PageBreak
        Section -Name "Naming Conventions" -Style 'Heading1' -ScriptBlock {
            Paragraph " "
            if ($sections."URL") {
                Section -Name "URL" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections."File") {
                Section -Name "File Naming" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections."Server") {
                Section -Name "Server Naming" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections.'Group') {
                PageBreak
                Section -Name 'Group Names' -Style Heading2 -ScriptBlock {
                    Paragraph "TBD"
                }
            }
        }
    }
    if ($sections."Security") {
        PageBreak     
        Section -Name "Security" -Style 'Heading1' -ScriptBlock {
            Paragraph "TBD"
            if ($sections."Servers and Processes") {
                Section -Name "Servers and Processes" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections."Data") {
                Section -Name "Data" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                    if ($sections."Data Classification") {
                        Section -Name "Data Classification" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                }
            }
            if ($sections."Authentication") {
                Section -Name "Authentication" -Style 'Heading2' -ScriptBlock {
                    if ($sections."Users") {
                        Section -Name "User Authenication" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                    if ($sections."Service Accounts") {
                        Section -Name "Service Accounts" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                    if ($sections."Certificates") {
                        Section -Name "Certificates" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                            Paragraph "TBD"
                        }
                    }
                }
            }

            if ($sections."Groups") {
                Section -Name "Groups" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections."Patching and Updates") {
                Section -Name "Patching and Updates" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
        }
    }
    if ($sections.'Solution Architecture') {
        PageBreak
        Section -Name "Solution Architecture" -Style 'Heading1' -ScriptBlock {
            Paragraph "TBD"

            if ($sections."Application Landscape") {
                Section -Name "Application Landscape" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD."
                    if ($sections.'Operating System Instances') {
                        Section "Operating System Instances" -Style 'Heading3' {
                            Paragraph "TBD."
                            Blankline -Count 1
                            Table -Object $osTable -Style listGrid
                        }
                    }
                    if ($sections.'Compute') {
                        Section "Compute" -Style 'Heading3' {
                            Paragraph "Server 1" -Bold
                            Table -Object $hardwareTable -List -Style listGrid -ColumnWidths 25, 75
                            Paragraph "Server 2:" -Bold
                            Table -Object $hardwareTable -List -Style listGrid -ColumnWidths 25, 75
                        }
                    }
                    if ($sections.'Other Software') {
                        PageBreak
                        Section "Other Software" -Style 'Heading3' {
                            Paragraph "TBD"
                            Paragraph "Software 1:" -Bold
                            Table -Object $softwareTable -List -Style listGrid -ColumnWidths 25, 75
                            Paragraph "Software 2:" -Bold
                            Table -Object $softwareTable -List -Style listGrid -ColumnWidths 25, 75
                        }
                    }
                    if ($sections."Clustering/High Availability") {
                        Section -Name "Clustering/High Availability" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                    if ($sections.'Protocols and Ports') {
                        Section -Name "Protocols and Ports" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                            Table -Object $portTable -Style listGrid

                        }
                    }
                    if ($sections.'Data Flows') {
                        Section -Name "Data Flows" -Style 'Heading3' -ScriptBlock {
                            Paragraph "Inputs:" -Bold
                            Paragraph "To be completed."
                            Paragraph "Outputs:" -Bold
                            Paragraph "To be completed."
                        }
                    } 
                }
            }
            if ($sections.'Network') {
                Section -Name "Network" -Style Heading2 -ScriptBlock {
                    if ($sections.'Logical Network') {
                        Section -Name "Logical Network" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                    if ($sections.'Physical Network') {
                        Section -Name "Physical Network" -Style 'Heading3' -ScriptBlock {
                            Paragraph "TBD"
                        }
                    }
                }
            }
            if ($sections."Enabled/Disabled Functionality") {
                Section -Name "Enabled/Disabled Functionality" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
        }
    }
 
    if ($sections."Operations and Support") {
        PageBreak
        Section -Name "Operations and Support" -Style 'Heading1' -ScriptBlock {
            Paragraph "TBD"
            if ($sections."Process Changes") {
                Section -Name "Process Changes" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                }
            }
            if ($sections."RACI Model") {
                Section -Name "RACI Model" -Style 'Heading2' -ScriptBlock {
                    Paragraph "Add Functions as necessary."
                    Table -Object $raciTable -Style listGrid
                }
            }
            if ($sections."Training") {
                Section -Name "Training" -Style 'Heading2' -ScriptBlock {
                    Paragraph "Describe any 3rd party or in house training that will be available."
                }
            }
            if ($sections."Vendor Support") {
                Section -Name "Vendor Support" -Style 'Heading2' -ScriptBlock {
                    Paragraph "Fill in the table for each solution component Vendor. "
                    Table -Object $vendorTable -Style listGrid
                }
            }
        }
    }
    if ($sections.'Implementation Guide') {
        PageBreak
        Section -Name "Implementation Guide" -Style 'Heading1' -ScriptBlock {
            Paragraph "TBD"
            if ($sections.'Modifications to Existing Infrastructure Systems and Configurations') {
                Section -Name "Modifications to Existing Infrastructure Systems and Configurations" -Style 'Heading2' -ScriptBlock {
                    Paragraph "To be completed"
                }
            }
            if ($sections.'New Infrastructure') {
                Section -Name "New Infrastructure" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                    if ($sections.'Hardware/VM') {
                        Section "New Hardware/VM" -Style 'Heading3' -ScriptBlock {
                            Paragraph "New Virtual and Physical Hardware:" -Bold
                            Paragraph "To be completed. Include details for all net new."
                        }
                    }
                    if ($sections.'Network') {
                        Section "Network Hardware" -Style 'Heading3' -ScriptBlock {
                            Paragraph "New Logical and Physical Network:" -Bold
                            Paragraph "To be completed. Include net new network items."
                        }
                    }
                }  
            }
            if ($sections.'Facilities Requirements') {
                Section "Facilities Requirements" -Style 'Heading2' -ScriptBlock {
                    Paragraph "TBD"
                    if ($sections.'Space Planning') {
                        Section "Space Planning" -Style 'Heading3' -ScriptBlock {
                            Paragraph "Data Center Space Requirements:" -Bold
                            Paragraph "TBD"
                            Paragraph "Office Area and Related Spaces:" -Bold
                            Paragraph "TBD"
                        }
                    }
                    if ($sections.'Architectural Systems') {
                        Section "Architectural Systems" -Style 'Heading3' -ScriptBlock {
                            Paragraph "Building Structure:" -Bold
                            Paragraph "TBD"
                            Paragraph "Interior Partitions:" -Bold
                            Paragraph "TBD"
                            Paragraph "Ceiling:" -Bold
                            Paragraph "TBD"
                            Paragraph "Raised Floor:" -Bold
                            Paragraph "TBD"
                            Paragraph "Cooling:" -Bold
                            Paragraph "TBD"
                        }
                    }
                    if ($sections.'Fire and Water Protection') {
                        Section "Fire and Water Protection" -Style 'Heading3' -ScriptBlock {
                            Paragraph "Fire Alarm:" -Bold
                            Paragraph "TBD"
                            Paragraph "Fire Suppressant:" -Bold
                            Paragraph "TBD"
                            Paragraph "Water Detection:" -Bold
                            Paragraph "TBD"
                            Paragraph "Humidity Monitoring:" -Bold
                            Paragraph "TBD"
                        }
                    }
                }
            }
        }
    }
    If ($sections.'APPENDICES') {
        PageBreak
 #From PScribo project examples.
       Section -Name "APPENDICES" -Style 'Heading1' -ScriptBlock {
            if ($sections.'EXAMPLE OF DYNAMICALLY GENERATED TABLE') {
                Section -Name "EXAMPLE OF DYNAMICALLY GENERATED TABLE" -Style 'Heading2' -ScriptBlock {
                    BlankLine -Count 2
                    Paragraph "This is an example of table data created dynamically that spans multiple pages and includes cell formatting."
                    Paragraph "Services ($($services.Count) Services found):" -Bold
                    $stoppedAutoServicesCell = $services.Clone()
                    $stoppedAutoServicesCell | Where-Object { $_.State -eq 'Stopped' -and $_.StartMode -eq 'Auto' } | Set-Style -Property State -Style StoppedService
                    $stoppedAutoServicesCell | Table -Columns DisplayName, State, StartMode -Headers 'Display Name', 'Status', 'Startup Type' -Tabs 1

                }
            }

        }    

    }

    Header -Default -IncludeOnFirstPage -NoSpace {
        $header = [Ordered] @{
            "$Team"        = "$FileName"
            "$Team Team__Style" = 'RightAligned'
        }
        Table -HashTable $header -Style Borderless -List
    }
    Footer -Default -NoSpace {
        Paragraph "Page <!# PageNumber #!> of <!# TotalPages #!>" -Style 'footer'
    }
}
try {
    $ThisDocument | Export-Document -Path "$Path" -Format $Format -PassThru:$PassThru
    Write-Host "Created $fullpath documents."
}
catch {
    Write-Host "Error Unable to create the Word document." -BackgroundColor 'RED' -ForegroundColor 'YELLOW'
}
Exit