Advertisement
Guest User

New-WelcomeLetter

a guest
Jun 9th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     #requires -Modules ActiveDirectory
  2.     <#
  3.     .Synopsis
  4.        Creates a welcome letter from a template
  5.     .DESCRIPTION
  6.        Creates a welcome letter from a temaplte, looks up active directory for user info then does string and hyperlink replacements on a template word document
  7.     .EXAMPLE
  8.        New-WelcomeLetter -SamAccountName 'ExampleUser'
  9.     .EXAMPLE
  10.        New-WelcomeLetter -SamAccountName 'ExampleUser' -NewPassword -Verbose
  11.     .EXAMPLE
  12.        New-WelcomeLetter -SamAccountName 'ExampleUser' -NewPassword -ChangePasswordAtNextLogon -Verbose
  13.     .AUTHOR
  14.         Created by /u/Sys_Ad_MN edited and turned into a function by /u/CSTW
  15.     #>
  16.     function New-WelcomeLetter
  17.     {
  18.         [CmdletBinding()]
  19.         [Alias()]
  20.         [OutputType([string])]
  21.         Param
  22.         (
  23.             # One or more SamAccountNames to generate a welcome letter for.
  24.             [Parameter(Mandatory=$true,
  25.                        ValueFromPipeline=$true,
  26.                        Position=0)]
  27.             [string[]]$SamAccountName,
  28.  
  29.             # Path to the template file that the replacments will be made on
  30.             [ValidateScript({test-path $_})]
  31.             [string]$Template = 'C:\temp\WelcomeLetters\Template.docx',
  32.  
  33.             # Directory where Welcome letters are saved
  34.             [ValidateScript({test-path $_})]
  35.             [string]$OutputDirectory = 'C:\temp\WelcomeLetters\',
  36.        
  37.             # Generates a new password and sets in Active Directory, if not specifed a generic message is used instead
  38.             [Switch]$NewPassword,
  39.  
  40.             # Enables the "Change password at next logon" setting in Active Directory. Has no effect unless -NewPassword if specified
  41.             [Switch]$ChangePasswordAtNextLogon
  42.         )
  43.  
  44.         Begin
  45.         {
  46.             #Variables for string replacements
  47.             $Forward = $True
  48.             $MatchCase = $True
  49.             $MatchWholeWord = $true
  50.             $MatchWildcards = $False
  51.             $MatchSoundsLike = $False
  52.             $MatchAllWordForms = $False  
  53.             $wdReplaceNone = 0
  54.             $wdFindContinue = 1
  55.             $wdReplaceAll = 2
  56.             $Wrap = $wdFindContinue
  57.             $Format = $False
  58.         }
  59.         Process
  60.         {
  61.             #Foreach and process block to allow for the $Samaccountname to be either piped in or supplied as an array
  62.             foreach($User in $SamAccountName) {
  63.                 Write-Verbose ""
  64.                 Write-verbose "Generating Welcome letter for $User"
  65.                 Write-Verbose ""
  66.                 #Get AD user details for replacements
  67.                 try
  68.                 {
  69.                     Write-Verbose "Getting user details from Active Directory"
  70.                     $ADUser = get-aduser $User -Properties EmailAddress, Title -ErrorAction Stop
  71.                 }
  72.                 catch
  73.                 {
  74.                     Write-Warning "Unable to get user details from Active Directory, Skipping Welcome letter creation for $User"
  75.                     Continue
  76.                 }
  77.                 #Assign this to make for easier formatting of verbose and warning messages
  78.                 $SamAccountName = $ADUser.SamAccountName
  79.  
  80.                 #If the NewPassword parameter was specified generate a password, otherwise uses the default text
  81.                 if($PSBoundParameters.ContainsKey('NewPassword')) {
  82.                
  83.                     #Generate password
  84.                     try
  85.                     {
  86.                         Write-Verbose 'Generating new password'
  87.                         #Excluded some months to make minimum password length 10 charachters with only 4 numbers.
  88.                         $Words = 'Summer', 'Winter','Autumn', 'Spring', 'January', 'February','August', 'September', 'October', 'November','December'                            
  89.                         $Random = New-Object System.Random
  90.                         $Word = $Words[$Random.Next(0,$Words.Count)]
  91.                         $Number = Get-Random -Minimum 1000 -Maximum 9999                
  92.                         $Password = "$Word$Number"
  93.                         $SecurePassword = ConvertTo-SecureString -string $Password -AsPlainText -Force
  94.                     }
  95.                     catch
  96.                     {
  97.                         Write-Warning "Failed to generate password. Skipping Welcome letter creation for $SamAccountName. `n`nError: $($Error[0])"
  98.                         Continue
  99.                     }
  100.  
  101.                     #Set account password in Active Directory
  102.                     try
  103.                     {
  104.                         Write-Verbose "Setting password in Active Directory for $SamAccountName"                  
  105.                         Set-ADAccountPassword -Identity $ADUser.SamAccountName -NewPassword $SecurePassword -Reset -whatif
  106.                         Write-Verbose "Successfully set password in Active Directory"
  107.  
  108.                         if($PSBoundParameters.ContainsKey('ChangePasswordAtNextLogon')) {
  109.                             try
  110.                             {
  111.                                 Write-Verbose "Setting ChangePasswordAtLogon option in Active Directory"
  112.                                 $ADUser | Set-ADUser -ChangePasswordAtLogon $True
  113.                             }
  114.                             catch
  115.                             {
  116.                                 Write-Warning "Failed to set change password at next logon option for $SamAccountName"
  117.                             }                        
  118.                         }                  
  119.                     }
  120.                     catch
  121.                     {
  122.                         Write-Warning "Failed to set account password. Using default text for password. `n`nError: $($Error[0])"
  123.                         $Password = 'If you have not been given your password please contact the Helpdesk'
  124.                     }
  125.                 }
  126.                 else #NewPassword parameter not specified
  127.                 {
  128.                     $Password = 'If you have not been given your password please contact the Helpdesk'
  129.                 }
  130.  
  131.                 [string]$OutputFilePath = join-path $OutputDirectory "$($ADUser.SamAccountName).docx"
  132.  
  133.                 $Replacements = @{'#FirstName#' = $ADUser.GivenName
  134.                                   '#LastName#'  = $ADUser.Surname
  135.                                   '#Title#'     = $ADUser.Title
  136.                                   '#PassWord#'  = $Password                              
  137.                                   }
  138.            
  139.                                      
  140.                 #Create a new Com object, load the template and assign the selection to a variable
  141.                 try
  142.                 {        
  143.                     Write-Verbose "Opening Word template"
  144.                     $WordObject = New-Object -comobject Word.Application -ErrorAction Stop -verbose:$False
  145.                     $WordObject.Visible = $True
  146.                     $DocumentObject = $WordObject.Documents.Open($Template) #path to word doc template
  147.                     $SelectionObject = $WordObject.Selection
  148.  
  149.                 }
  150.                 catch
  151.                 {
  152.                     Write-Warning "Unable to open the template file: $Template, Skipping Welcome letter creation for $SamAccountName"
  153.                     Continue
  154.                 }
  155.  
  156.                 #Make string replacements
  157.                 foreach($Key in $Replacements.Keys) {
  158.                     Write-Verbose "Replacing string $Key"            
  159.                     try
  160.                     {
  161.                         $FindText = $Key
  162.                         $ReplaceWith = $Replacements.$Key
  163.  
  164.                         $MakeReplacement = $SelectionObject.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
  165.  
  166.                         if($SelectionObject.Find.Found)
  167.                         {
  168.                             Write-Verbose "String was replaced with: $ReplaceWith"
  169.                         }
  170.                         else
  171.                         {
  172.                             Write-Warning "Did not find the string $Key in the template: $Template"
  173.                         }
  174.                     }
  175.                     catch
  176.                     {
  177.                         Write-Warning "Failed string replacement in template file: $Template for string: $Key"
  178.                     }
  179.                 } #end foreach $Replacements.Keys
  180.  
  181.                 #Edit the hyperlinks of email addresses              
  182.                 $OldHyperlink = “mailto:#EmailAddress#”
  183.                 $NewHyperlink = "Mailto:$($ADUser.EmailAddress)"
  184.  
  185.                 Write-Verbose "Replacing hyperlinks with email address: $($ADUser.EmailAddress)"
  186.                 foreach($HyperLinkObject in $DocumentObject.Hyperlinks) {
  187.                     if($HyperLinkObject.address -eq $OldHyperlink)
  188.                     {    
  189.                         $HyperLinkObject.Address = $HyperLinkObject.Address -Replace $OldHyperlink, $NewHyperlink
  190.                     }
  191.                 }
  192.  
  193.                 #Save the document
  194.                 try
  195.                 {
  196.                     Write-Verbose "Saving welcome letter to $OutputFilePath"
  197.                     $DocumentObject.SaveAs([ref] $OutputFilePath)
  198.                 }
  199.                 catch
  200.                 {
  201.                     Write-Error "Failed to save the new Word document. `n`nError: $($Error[0])"
  202.                 }
  203.            
  204.                 #Close the document
  205.                 try
  206.                 {
  207.                     Write-Verbose "Closing Word docuemnt"
  208.                     $WordObject.quit()
  209.                 }
  210.                 catch
  211.                 {
  212.                     Write-Warning "Failed to close Word document. `n`nError: $($Error[0])"
  213.                     Continue  
  214.                 }
  215.  
  216.             } #end foreach samaccountname
  217.         }
  218.         End
  219.         {
  220.             Write-Output $OutputFilePath
  221.         }
  222.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement