Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #requires -Modules ActiveDirectory
- <#
- .Synopsis
- Creates a welcome letter from a template
- .DESCRIPTION
- 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
- .EXAMPLE
- New-WelcomeLetter -SamAccountName 'ExampleUser'
- .EXAMPLE
- New-WelcomeLetter -SamAccountName 'ExampleUser' -NewPassword -Verbose
- .EXAMPLE
- New-WelcomeLetter -SamAccountName 'ExampleUser' -NewPassword -ChangePasswordAtNextLogon -Verbose
- .AUTHOR
- Created by /u/Sys_Ad_MN edited and turned into a function by /u/CSTW
- #>
- function New-WelcomeLetter
- {
- [CmdletBinding()]
- [Alias()]
- [OutputType([string])]
- Param
- (
- # One or more SamAccountNames to generate a welcome letter for.
- [Parameter(Mandatory=$true,
- ValueFromPipeline=$true,
- Position=0)]
- [string[]]$SamAccountName,
- # Path to the template file that the replacments will be made on
- [ValidateScript({test-path $_})]
- [string]$Template = 'C:\temp\WelcomeLetters\Template.docx',
- # Directory where Welcome letters are saved
- [ValidateScript({test-path $_})]
- [string]$OutputDirectory = 'C:\temp\WelcomeLetters\',
- # Generates a new password and sets in Active Directory, if not specifed a generic message is used instead
- [Switch]$NewPassword,
- # Enables the "Change password at next logon" setting in Active Directory. Has no effect unless -NewPassword if specified
- [Switch]$ChangePasswordAtNextLogon
- )
- Begin
- {
- #Variables for string replacements
- $Forward = $True
- $MatchCase = $True
- $MatchWholeWord = $true
- $MatchWildcards = $False
- $MatchSoundsLike = $False
- $MatchAllWordForms = $False
- $wdReplaceNone = 0
- $wdFindContinue = 1
- $wdReplaceAll = 2
- $Wrap = $wdFindContinue
- $Format = $False
- }
- Process
- {
- #Foreach and process block to allow for the $Samaccountname to be either piped in or supplied as an array
- foreach($User in $SamAccountName) {
- Write-Verbose ""
- Write-verbose "Generating Welcome letter for $User"
- Write-Verbose ""
- #Get AD user details for replacements
- try
- {
- Write-Verbose "Getting user details from Active Directory"
- $ADUser = get-aduser $User -Properties EmailAddress, Title -ErrorAction Stop
- }
- catch
- {
- Write-Warning "Unable to get user details from Active Directory, Skipping Welcome letter creation for $User"
- Continue
- }
- #Assign this to make for easier formatting of verbose and warning messages
- $SamAccountName = $ADUser.SamAccountName
- #If the NewPassword parameter was specified generate a password, otherwise uses the default text
- if($PSBoundParameters.ContainsKey('NewPassword')) {
- #Generate password
- try
- {
- Write-Verbose 'Generating new password'
- #Excluded some months to make minimum password length 10 charachters with only 4 numbers.
- $Words = 'Summer', 'Winter','Autumn', 'Spring', 'January', 'February','August', 'September', 'October', 'November','December'
- $Random = New-Object System.Random
- $Word = $Words[$Random.Next(0,$Words.Count)]
- $Number = Get-Random -Minimum 1000 -Maximum 9999
- $Password = "$Word$Number"
- $SecurePassword = ConvertTo-SecureString -string $Password -AsPlainText -Force
- }
- catch
- {
- Write-Warning "Failed to generate password. Skipping Welcome letter creation for $SamAccountName. `n`nError: $($Error[0])"
- Continue
- }
- #Set account password in Active Directory
- try
- {
- Write-Verbose "Setting password in Active Directory for $SamAccountName"
- Set-ADAccountPassword -Identity $ADUser.SamAccountName -NewPassword $SecurePassword -Reset -whatif
- Write-Verbose "Successfully set password in Active Directory"
- if($PSBoundParameters.ContainsKey('ChangePasswordAtNextLogon')) {
- try
- {
- Write-Verbose "Setting ChangePasswordAtLogon option in Active Directory"
- $ADUser | Set-ADUser -ChangePasswordAtLogon $True
- }
- catch
- {
- Write-Warning "Failed to set change password at next logon option for $SamAccountName"
- }
- }
- }
- catch
- {
- Write-Warning "Failed to set account password. Using default text for password. `n`nError: $($Error[0])"
- $Password = 'If you have not been given your password please contact the Helpdesk'
- }
- }
- else #NewPassword parameter not specified
- {
- $Password = 'If you have not been given your password please contact the Helpdesk'
- }
- [string]$OutputFilePath = join-path $OutputDirectory "$($ADUser.SamAccountName).docx"
- $Replacements = @{'#FirstName#' = $ADUser.GivenName
- '#LastName#' = $ADUser.Surname
- '#Title#' = $ADUser.Title
- '#PassWord#' = $Password
- }
- #Create a new Com object, load the template and assign the selection to a variable
- try
- {
- Write-Verbose "Opening Word template"
- $WordObject = New-Object -comobject Word.Application -ErrorAction Stop -verbose:$False
- $WordObject.Visible = $True
- $DocumentObject = $WordObject.Documents.Open($Template) #path to word doc template
- $SelectionObject = $WordObject.Selection
- }
- catch
- {
- Write-Warning "Unable to open the template file: $Template, Skipping Welcome letter creation for $SamAccountName"
- Continue
- }
- #Make string replacements
- foreach($Key in $Replacements.Keys) {
- Write-Verbose "Replacing string $Key"
- try
- {
- $FindText = $Key
- $ReplaceWith = $Replacements.$Key
- $MakeReplacement = $SelectionObject.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
- if($SelectionObject.Find.Found)
- {
- Write-Verbose "String was replaced with: $ReplaceWith"
- }
- else
- {
- Write-Warning "Did not find the string $Key in the template: $Template"
- }
- }
- catch
- {
- Write-Warning "Failed string replacement in template file: $Template for string: $Key"
- }
- } #end foreach $Replacements.Keys
- #Edit the hyperlinks of email addresses
- $OldHyperlink = “mailto:#EmailAddress#”
- $NewHyperlink = "Mailto:$($ADUser.EmailAddress)"
- Write-Verbose "Replacing hyperlinks with email address: $($ADUser.EmailAddress)"
- foreach($HyperLinkObject in $DocumentObject.Hyperlinks) {
- if($HyperLinkObject.address -eq $OldHyperlink)
- {
- $HyperLinkObject.Address = $HyperLinkObject.Address -Replace $OldHyperlink, $NewHyperlink
- }
- }
- #Save the document
- try
- {
- Write-Verbose "Saving welcome letter to $OutputFilePath"
- $DocumentObject.SaveAs([ref] $OutputFilePath)
- }
- catch
- {
- Write-Error "Failed to save the new Word document. `n`nError: $($Error[0])"
- }
- #Close the document
- try
- {
- Write-Verbose "Closing Word docuemnt"
- $WordObject.quit()
- }
- catch
- {
- Write-Warning "Failed to close Word document. `n`nError: $($Error[0])"
- Continue
- }
- } #end foreach samaccountname
- }
- End
- {
- Write-Output $OutputFilePath
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement