Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codeman65
Forked from anonymous/New-UserOnboarding.ps1
Last active October 19, 2015 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeman65/24777394b180c1bb9afe to your computer and use it in GitHub Desktop.
Save codeman65/24777394b180c1bb9afe to your computer and use it in GitHub Desktop.
#GUI Elements inspired by Powershell GUI toolmaking series on http://foxdeploy.com/
#Not on PowerShell 3.0+, uncomment following line
#import-module activedirectory
#Random Password Function by http://blog.oddbit.com/2012/11/04/powershell-random-passwords/
Function random-password ($length = 8)
{
$punc = 46..46
$digits = 48..57
$letters = 65..90 + 97..122
# Thanks to
# https://blogs.technet.com/b/heyscriptingguy/archive/2012/01/07/use-pow
$password = get-random -count $length `
-input ($punc + $digits + $letters) |
% -begin { $aa = $null } `
-process {$aa += [char]$_} `
-end {$aa}
return $password
}
#Calling GeneratePassword Method and storing in a varible
$newpassword = random-password
#Import Exchange cmdlets
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<exchangeserver>/PowerShell/ -Authentication Kerberos
Import-PSSession $Session
#Define GUI
#ERASE ALL THIS AND PUT XAML BELOW between the @" "@
$inputXML = @"
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="New User Onboarding" Height="350" Width="525">
<Grid>
<Image x:Name="image" HorizontalAlignment="Left" Height="100" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" Source="<logo>"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="138,21,0,0" TextWrapping="Wrap" Text="This tool is used to create new employee active directory accounts, enable their mailbox, and generate an onboarding letter containing useful information. All fields are required." VerticalAlignment="Top" Height="89" Width="354"/>
<Button x:Name="submitbutton" Content="Submit" HorizontalAlignment="Left" Margin="433,271,0,0" VerticalAlignment="Top" Width="75" Height="40"/>
<Label x:Name="label" Content="First Name" HorizontalAlignment="Left" Margin="10,154,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="firstname_textBox" HorizontalAlignment="Left" Height="23" Margin="92,158,0,0" TextWrapping="Wrap" Text="FIrst Name" VerticalAlignment="Top" Width="120"/>
<Label x:Name="label1" Content="Username" HorizontalAlignment="Left" Margin="7,192,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.437,-0.056"/>
<Label x:Name="label2" Content="Mailbox Database" HorizontalAlignment="Left" Margin="10,268,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.014,-0.756"/>
<Label x:Name="label3" Content="Last Name" HorizontalAlignment="Left" Margin="226,158,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="lastname_textBox" HorizontalAlignment="Left" Height="23" Margin="354,158,0,0" TextWrapping="Wrap" Text="Last Name" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="username_textBox" HorizontalAlignment="Left" Height="23" Margin="92,192,0,0" TextWrapping="Wrap" Text="Windows Username" VerticalAlignment="Top" Width="120"/>
<Label x:Name="label4" Content="Organizational Unit" HorizontalAlignment="Left" Margin="226,192,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="ou_comboBox" HorizontalAlignment="Left" Margin="354,195,0,0" VerticalAlignment="Top" Width="120"/>
<ComboBox x:Name="database_comboBox" HorizontalAlignment="Left" Margin="127,271,0,0" VerticalAlignment="Top" Width="120"/>
<Label x:Name="label5" HorizontalAlignment="Left" Margin="92,220,0,0" VerticalAlignment="Top" Visibility="Hidden"/>
<Button x:Name="CopyUserButton" Content="Copy User" HorizontalAlignment="Left" Margin="433,271,0,0" VerticalAlignment="Top" Width="75" Height="40" IsEnabled="False" Visibility="Hidden"/>
<CheckBox x:Name="CopyUser_CheckBox" Content="Copy Existing User" HorizontalAlignment="Left" Margin="10,248,0,0" VerticalAlignment="Top"/>
<Label x:Name="label6" Content="Source User" HorizontalAlignment="Left" Margin="226,245,0,0" VerticalAlignment="Top" Visibility="Hidden"/>
<TextBox x:Name="SourceUser_textbox" HorizontalAlignment="Left" Height="23" Margin="354,243,0,0" TextWrapping="Wrap" Text="Existing User" VerticalAlignment="Top" Width="120" Visibility="Hidden"/>
</Grid>
</Window>
"@
$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window'
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."}
#===========================================================================
# Load XAML Objects In PowerShell
#===========================================================================
$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}
Function Get-FormVariables{
if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true}
write-host "Found the following interactable elements from our form" -ForegroundColor Cyan
get-variable WPF*
}
Get-FormVariables
#===========================================================================
# Actually make the objects work
#===========================================================================
#Load Orgnizational Units we want to use into an array
$ous = (get-adobject -SearchBase "<baseOU>" -filter 'ObjectClass -eq "organizationalUnit"') | select DistinguishedName
$defaultOU = (get-adobject -filter 'ObjectClass -eq "domain"' -Properties wellKnownObjects).wellknownobjects.Split("`n")[-0].Split(':') | select -Last 1
$ous | ForEach-Object {$_.DistinguishedName} | ForEach-Object {$WPFou_comboBox.AddChild($_)}
"<additionalOU>","<additionalOU>" | ForEach-object {$WPFou_comboBox.AddChild($_)}
$database = (get-mailboxdatabase -Server <exchange server>) | select name
$database | ForEach-Object {$_.Name} | ForEach-Object {$WPFdatabase_comboBox.AddChild($_)}
#Populate variables from combo boxes
$WPFusername_textBox.add_GotKeyboardFocus({
$WPFusername_textBox.SelectAll()
})
$WPFfirstname_textBox.add_GotKeyboardFocus({
$WPFfirstname_textBox.SelectAll()
})
$WPFlastname_textBox.add_GotKeyboardFocus({
$WPFlastname_textBox.SelectAll()
})
$WPFCopyUser_CheckBox.Add_Checked({
$WPFsubmitbutton.Visibility = 'Hidden'
$WPFCopyUserButton.Visibility = 'Visible'
$WPFCopyUserButton.IsEnabled = $True
$WPFSourceUser_textbox.Visibility = 'Visible'
$WPFlabel6.Visibility = 'Visible'
})
$WPFCopyUser_CheckBox.Add_UnChecked({
$WPFsubmitbutton.Visibility = 'Visible'
$WPFCopyUserButton.Visibility = 'Hidden'
$WPFCopyUserButton.IsEnabled = $False
$WPFSourceUser_textbox.Visibility = 'Hidden'
$WPFlabel6.Visibility = 'Hidden'
})
$WPFusername_textBox.add_LostFocus({
$user = $WPFusername_textBox.Text
$user
if (Get-ADUser -Filter {samaccountname -eq $user} ) {
# Exists
$WPFlabel5.Visibility = 'Visible'
$WPFlabel5.Background = '#FFEBFF00'
$WPFlabel5.Content = "Username in use"
$WPFsubmitbutton.Visibility = 'Hidden'
}
else {
# Doesn't Exist
$WPFlabel5.Visibility = 'Visible'
$WPFlabel5.Background = "#00FFFFFF"
$WPFlabel5.Content = "Username available"
$WPFsubmitbutton.Visibility = 'Visible'
}
})
function Get-FormFields {
$location = if ($WPFou_comboBox.Text -ne $null){$WPFou_comboBox.Text}else{$defaultOU}
$HashArguments =
@{ Name = $WPFfirstname_textBox.Text + " " + $WPFlastname_textBox.Text;
GivenName=$WPFfirstname_textBox.Text;
SurName = $WPFlastname_textBox.Text;
AccountPassword=($newpassword | ConvertTo-SecureString -AsPlainText -Force);
DisplayName=$WPFfirstname_textBox.Text + " " + $WPFlastname_textBox.Text;
SamAccountName = $WPFusername_textBox.Text;
UserPrincipalName = $WPFusername_textBox.Text + "@domain.com";
Path=$location;
}
$HashArguments
}
function Get-FormCopyFields {
$copyuser = get-aduser $WPFSourceUser_textbox.text
$location = if ($WPFou_comboBox.Text -ne $null){$WPFou_comboBox.Text}else{$defaultOU}
$HashArguments =
@{ Name = $WPFfirstname_textBox.Text + " " + $WPFlastname_textBox.Text;
GivenName=$WPFfirstname_textBox.Text;
SurName = $WPFlastname_textBox.Text;
AccountPassword=($newpassword | ConvertTo-SecureString -AsPlainText -Force);
DisplayName=$WPFfirstname_textBox.Text + " " + $WPFlastname_textBox.Text;
SamAccountName = $WPFusername_textBox.Text;
UserPrincipalName = $WPFusername_textBox.Text + "@domain.com";
Path=$location;
}
$HashArguments
}
function Get-ExchangeFields {
$database = $WPFdatabase_comboBox.Text
$ExHash =
@{ Identity = $WPFusername_textBox.Text;
Database = $database;
}
$ExHash
}
$WPFsubmitbutton.Add_Click({
#Resolve Form Settings
$hash = Get-FormFields
New-ADUser @hash -PassThru -Enabled:$true -ChangePasswordAtLogon:$true
start-sleep -Seconds 30
$ExchangeHash = Get-ExchangeFields
Enable-Mailbox @ExchangeHash
$Form.Close()})
$WPFCopyUserButton.Add_Click({
#Resolve Form Settings
$hash = Get-FormCopyFields
New-ADUser @hash -PassThru -Enabled:$true -ChangePasswordAtLogon:$true
Add-ADPrincipalGroupMembership -id $WPFusername_textBox.Text -MemberOf (Get-ADPrincipalGroupMembership -id $copyuser | ? {$_.name -notmatch "Domain *"})
start-sleep -Seconds 30
$ExchangeHash = Get-ExchangeFields
Enable-Mailbox @ExchangeHash
$Form.Close()})
#===========================================================================
# Shows the form
#===========================================================================
write-host "To show the form, run the following" -ForegroundColor Cyan
'$Form.ShowDialog() | out-null'
$Form.ShowDialog() | out-null
#Define Variables for AD Account that are populated via GUI
$firstname = $WPFfirstname_textBox.Text
$lastname = $WPFlastname_textBox.Text
$empname = $firstname + " " + $lastname
$newuser = $WPFusername_textBox.Text
#Creating Word Onboarding Document
$word = new-object -ComObject "Word.Application"
$doc = $word.documents.Add()
#$word.Visible = $true
#Set header image
$wdSeekPrimaryHeader = 1
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$selection = $word.Selection
$objShape = $Selection.InlineShapes.AddPicture("<image path here>")
#Leave header section
$wdSeekPrimaryHeader = 0
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
#Start creating document
$wdAlignParagraphRight = 2
$selection.ParagraphFormat.Alignment=$wdAlignParagraphRight
$selection.TypeText((get-date))
$selection.TypeParagraph()
$wdAlignParagraphRight = 0
$selection.ParagraphFormat.Alignment=$wdAlignParagraphRight
$selection.TypeText(("<word doc text> $($empname). <word doc text>"))
$selection.TypeText(("<word doc text>"))
$selection.TypeParagraph()
$selection.Font.Bold=$True
$selection.TypeText(("Your Network and E-Mail username is: "))
$selection.Font.Bold=$False
$selection.TypeText(("$($newuser)"))
$selection.TypeParagraph()
$selection.Font.Bold=$True
$selection.TypeText(("Your one-time password is: "))
$selection.Font.Bold=$False
$selection.TypeText(("$($newpassword)"))
$doc.SaveAs([ref]"C:\temp\$($newuser)_onboarding.docx")
$doc.Close()
$word.Quit()
Send-MailMessage -Subject "<email subject>" -Body "<email body>" -Attachments <filepath>\"$newuser"_onboarding.docx -from <from address> -SmtpServer <smtpserver> -to <email address>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment