Create an user
This script creates a new ad user based on the following:
- display a gui form for information about the user
- determines the username based on company standards
- Sets some AD and profiles/home folder information based on the location of the user
- sets the default AD groups
- creates a mailbox for the users
- creates homefolders and profile folders
- creates a welcome note for the user, based on the users information
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
# Location of the files belonging to this script $path = '\\srbdc1\powershellrepository$\UserManagement' # Log file $log = $path + '\create_ad_users.log' # Current username for logging $currentuser = $Env:USERNAME # Current Date $date = Get-Date function Add-MWUser { # Defining the parameters needed for creating the new user. # Help messages are not nessesary as this function is populated true a form. Param ( # Param1 Voornaam [Parameter(Mandatory = $true)] [String] $Voornaam, # Param2 Tussevoegsel [String] $Tussenvoegsel, # Param3 help description [Parameter(Mandatory = $true)] [String] $Achternaam, [String] [Parameter(Mandatory = $true)] [ValidateSet('BHW', 'DRS', 'Roosendaal')] $Locatie, [Parameter(Mandatory = $true)] [String] $Titel, [String] $Telefoonnummer, [String] $mobielnummer, [Parameter(Mandatory = $true)] [String] $Afdeling, [String] $OWAAccess = $false, [String] $MobileAccess = $false ) Begin # this BEGIN block is executed in front of the proces. { # Defining variables $Spatie = ' ' $DefaultPassword = 'Welkom01' $DomainDN = (Get-ADDomain).DistinguishedName $dnsroot = (Get-ADDomain).DNSRoot $netbiosname = (Get-ADDomain).NETBIOSNAME $OULocation = 'OU=Company' $CASserver = 'srbhwcas001' $datum = Get-Date -Format D } Process # This PROCESS block executes the creation of the user { # Putting the provided information in the logfile "[INFO]`t Voornaam : $Voornaam" | Out-File -FilePath $log -Append "[INFO]`t Tussevoegsels : $Tussenvoegsel" | Out-File -FilePath $log -Append "[INFO]`t Achternaam : $Achternaam" | Out-File -FilePath $log -Append "[INFO]`t Functie : $Titel" | Out-File -FilePath $log -Append "[INFO]`t Locatie : $Locatie" | Out-File -FilePath $log -Append "[INFO]`t Afdeling : $Afdeling" | Out-File -FilePath $log -Append "[INFO]`t Telefoonnummer : $Telefoonnummer" | Out-File -FilePath $log -Append "[INFO]`t Mobiel nummer : $mobielnummer" | Out-File -FilePath $log -Append # Set values based on the provided location # This infomation is used in the Active Directory and determinse on witch server the userprofile is located. if ($Locatie -eq 'BHW') { $Straat = 'Badhuisweg 108' $Zip = '2587 CM' $Stad = 'Den Haag' $Provincy = 'ZH' $profilepath = '\\srbfp1\profiles$' $Homefolderpath = '\\srbfp1\users$' $DefaultADGroup = 'Badhuisweg' } elseif ($Locatie -eq 'DRS') { $Straat = 'De Ruijterstraat 53' $Zip = '2518 AN' $Stad = 'Den Haag' $Provincy = 'ZH' $profilepath = '\\srddc1\profiles$' $Homefolderpath = '\\srddc1\users$' $DefaultADGroup = 'AfdelingTB' } elseif ($Locatie -eq 'Roosendaal') { $Straat = 'H.G. Dirkxstraat 1' $Zip = '4701 AV' $Stad = 'Roosendaal' $Provincy = 'NB' $profilepath = '\\srrdc1\profiles$' $Homefolderpath = '\\srrdc1\users$' $DefaultADGroup = 'Roosendaal' } # Cleaning up spaces in names "[INFO]`t Creating a username" | Out-File -FilePath $log -Append $VolledigeAchternaam = $Tussenvoegsel+$Spatie+$Achternaam $nospacestussenvoegsel = $Tussenvoegsel.Replace($Spatie,'') $Tussenvoegsel = $nospacestussenvoegsel $nospacesachternaam = $Achternaam.Replace($Spatie,'') $Achternaam = $nospacesachternaam $Username = ('{0}{1}{2}' -f $Voornaam.SubString(0, 1), $nospacestussenvoegsel, $nospacesachternaam) # Check is username is available $EaPrefBefore = $ErrorActionPreference $ErrorActionPreference = 'SilentlyContinue' try { if (Get-ADUser -Identity $Username) { # Try a different format of the username is the original is taken. $Username = ('{0}{1}{2}' -f $Voornaam.SubString(0, 1), $nospacestussenvoegsel.Substring(0, 1), $nospacesachternaam) if (Get-ADUser -Identity $Username) { # Log an error if the username is not availible and stop the program. '[ERROR] Geen bruikbare gebruikersnaam gevonden' | Out-File -FilePath $log -Append return } } } Catch { } # Define the parameters in a parameter block for the useraccount $ErrorActionPreference = $EaPrefBefore $NewUserParams = @{ 'Name' = $Voornaam + $Spatie + $VolledigeAchternaam 'GivenName' = $Voornaam 'Surname' = $VolledigeAchternaam 'Title' = $Titel 'SamAccountname' = $Username 'UserPrincipalName' = $Username + '@' + $dnsroot 'AccountPassword' = (ConvertTo-SecureString -AsPlainText -String $DefaultPassword -Force) 'Enabled' = $true 'Path' = ('OU=Users,OU={0},{1},{2}' -f $Locatie, $OULocation, $DomainDN) 'ChangePasswordAtLogon' = $true 'Postalcode' = $Zip 'City' = $Stad 'State' = $Provincy 'Streetaddress' = $Straat 'Country' = 'NL' 'Company' = 'Company' 'Department' = $Afdeling 'Description' = $Titel 'Displayname' = $Voornaam + $Spatie + $VolledigeAchternaam 'Homedirectory' = $Homefolderpath + '\' + $Username 'ProfilePath' = $profilepath + '\' + $Username + '.V2' 'HomeDrive' = 'P:' 'MobilePhone' = $mobielnummer 'OfficePhone' = $Telefoonnummer } "[INFO]`t Creating user account" | Out-File -FilePath $log -Append # Creating the useraccount based on the parameterblock New-ADUser @NewUserParams # Add the user to the default usergroups "[INFO]`t Adding Groupmemberships" | Out-File -FilePath $log -Append Add-ADGroupMember -Identity Algemeen -Members $Username Add-ADGroupMember -Identity medewerkers -Members $Username Add-ADGroupMember -Identity $DefaultADGroup -Members $Username "[INFO]`t Creating Home and Profile folders" | Out-File -FilePath $log -Append $aduser = ('{0}\{1}' -f $netbiosname, $Username) # Create the profile folder, based on the username New-Item -Path $profilepath -Name "$($Username).V2" -ItemType Directory # Setting the folderrights $acl = Get-Acl -Path "$($profilepath)\$($Username).V2" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($aduser, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow') $acl.AddAccessRule($rule) Set-Acl -Path "$($profilepath)\$($Username).V2" -AclObject $acl # Create the profile folder, based on the username New-Item -Path $Homefolderpath -Name $Username -ItemType Directory # Setting the folderrights $acl = Get-Acl -Path "$($Homefolderpath)\$($Username)" $rule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList ($aduser, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow') $acl.AddAccessRule($rule) Set-Acl -Path "$($Homefolderpath)\$($Username)" -AclObject $acl # Create the emailaddress $mailbox = $Voornaam.substring(0,1).ToLower() + '.' + $nospacestussenvoegsel.ToLower() +$nospacesachternaam.ToLower() + '@' + $dnsroot Try { "[INFO]`t Creating mailbox " | Out-File -FilePath $log -Append # Connect to Excahnge for creating the mailbox. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$CASserver/PowerShell/ -Authentication Kerberos Import-PSSession $Session -AllowClobber # Create Mailbox for the user Enable-Mailbox -Identity $Username -Database DAG001_Mailstore1 -PrimarySmtpAddress $mailbox # Disable OWA and Mobile access to the mailbox. Default company policy for the first month. Get-CASMailbox -Identity $Username | Set-CASMailbox -OWAEnabled $false -ActiveSyncEnabled $false -OWAforDevicesEnabled $false } Catch { "[ERROR]`t Couldn't create the users mailbox : $($_.Exception.Message)" | Out-File -FilePath $log -Append } # Creating a welcome document for the user '[INFO] Create the Welcome note for the user' | Out-File -FilePath $log -Append $wdReplaceAll = 2 $wdFindContinue = 1 $MatchCase = $false $MatchWholeWord = $true $MatchWildcards = $false $MatchSoundsLike = $false $MatchAllWordForms = $false $Forward = $true $Wrap = $wdFindContinue $Format = $false $objWord = New-Object -ComObject Word.Application $objWord.Visible = $true # Open word document for editing $objDoc = $objWord.Documents.Open("\\srbdc1\powershellrepository$\UserManagement\Welkomstbrief.docx") $objSelection = $objWord.Selection # Replacing text in document with values from the created user $FindText = '[name]' $ReplaceWith = "$Voornaam $VolledigeAchternaam" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = '[username]' $ReplaceWith = "$Username" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = '[date]' $ReplaceWith = "$datum" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = '[voornaam]' $ReplaceWith = "$Voornaam" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = '[defaultpassword]' $ReplaceWith = "$DefaultPassword" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = '[emailaddress]' $ReplaceWith = "$mailbox" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) # TODO: Open a word document with the remaning actions to perform <#> $objWord = New-Object -comobject Word.Application $objWord.Visible = $True $objDoc = $objWord.Documents.Open("\\srbdc1\powershellrepository$\UserManagement\ResterendeActies.docx") $FindText = "[emailaddress]" $ReplaceWith = "$mailbox" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = "[name]" $ReplaceWith = "$voornaam $VolledigeAchternaam" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = "[afdeling]" $ReplaceWith = "$Afdeling" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) $FindText = "[date]" $ReplaceWith = "$datum" $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll) </#> } End { # Clean up session to the exchange server Remove-PSSession -ComputerName srbhwcas001 } } #region XAML window definition # Windows Form for defining user input $xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinWidth="200" Width ="600" SizeToContent="Height" Title="Aanmaken nieuwe medewerker" Topmost="True"> <Grid Margin="10,40,10,10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Image Source="http://url to logo.jpg" Width="100" Height="50" Grid.RowSpan="1" Margin="5,0" /> <TextBlock Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Margin="5">Voer de informatie van de nieuwe medewerker in:</TextBlock> <TextBlock Grid.Column="0" Grid.Row="3" Margin="5">Voornaam</TextBlock> <TextBlock Grid.Column="0" Grid.Row="4" Margin="5">Tussenvoegsels</TextBlock> <TextBlock Grid.Column="0" Grid.Row="5" Margin="5">Achternaam</TextBlock> <TextBlock Grid.Column="0" Grid.Row="6" Margin="5">Locatie</TextBlock> <TextBlock Grid.Column="0" Grid.Row="7" Margin="5">Afdeling</TextBlock> <TextBlock Grid.Column="0" Grid.Row="8" Margin="5">Functie</TextBlock> <TextBlock Grid.Column="0" Grid.Row="9" Margin="5">Telefoonnummer</TextBlock> <TextBlock Grid.Column="0" Grid.Row="10" Margin="5">Mobielnummer</TextBlock> <TextBox Name="TxtVoornaam" Grid.Column="1" Grid.Row="3" Margin="5"></TextBox> <TextBox Name="TxtTussenvoegsel" Grid.Column="1" Grid.Row="4" Margin="5"></TextBox> <TextBox Name="TxtAchternaam" Grid.Column="1" Grid.Row="5" Margin="5"></TextBox> <ComboBox Name="TxtLocatie" Grid.Column="1" Grid.Row="6" Margin="5"> <ComboBoxItem IsSelected="True">BHW</ComboBoxItem> <ComboBoxItem>DRS</ComboBoxItem> <ComboBoxItem>Roosendaal</ComboBoxItem> </ComboBox> <ComboBox Name="TxtAfdeling" Grid.Column="1" Grid.Row="7" Margin="5"> <ComboBoxItem>Acquisitie - assetmanagement - Duitsland</ComboBoxItem> <ComboBoxItem>Administratie</ComboBoxItem> <ComboBoxItem>Algemene zaken - PenO</ComboBoxItem> <ComboBoxItem>Automatisering</ComboBoxItem> <ComboBoxItem>Bedrijfshuisvesting</ComboBoxItem> <ComboBoxItem>Beheer Bedrijfsmatig Vastgoed</ComboBoxItem> <ComboBoxItem>Beheer woningen</ComboBoxItem> <ComboBoxItem>Beveiliging</ComboBoxItem> <ComboBoxItem>Catering</ComboBoxItem> <ComboBoxItem>Directie</ComboBoxItem> <ComboBoxItem>Directie - Management</ComboBoxItem> <ComboBoxItem>Duitsland</ComboBoxItem> <ComboBoxItem>Facilitaire Dienst</ComboBoxItem> <ComboBoxItem>Personeelszaken</ComboBoxItem> <ComboBoxItem>Receptie</ComboBoxItem> <ComboBoxItem>Treasury</ComboBoxItem> <ComboBoxItem>Verhuur</ComboBoxItem> <ComboBoxItem>Verkoop</ComboBoxItem> <ComboBoxItem>Algemeen TB</ComboBoxItem> <ComboBoxItem>Management TB</ComboBoxItem> <ComboBoxItem>Opzichters TB</ComboBoxItem> <ComboBoxItem>Projectleiding TB</ComboBoxItem> <ComboBoxItem>Servicedesk</ComboBoxItem> <ComboBoxItem>VVE</ComboBoxItem> <ComboBoxItem>Wassenaar</ComboBoxItem> <ComboBoxItem>Roosendaal</ComboBoxItem> </ComboBox> <TextBox Name="TxtTitel" Grid.Column="1" Grid.Row="8" Margin="5"></TextBox> <TextBox Name="TxtTelefoonnummer" Grid.Column="1" Grid.Row="9" Margin="5"></TextBox> <TextBox Name="TxtMobielnummer" Grid.Column="1" Grid.Row="10" Margin="5"></TextBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,10,0,0" Grid.Row="11" Grid.ColumnSpan="2"> <Button Name="ButOk" MinWidth="80" Height="22" Margin="5">OK</Button> <Button Name="ButCancel" MinWidth="80" Height="22" Margin="5">Cancel</Button> </StackPanel> </Grid> </Window> '@ #endregion #region Code Behind function Convert-XAMLtoWindow { param ( [Parameter(Mandatory)] [string] $xaml, [string[]] $NamedElement = $null, [switch] $PassThru ) Add-Type -AssemblyName PresentationFramework $reader = [XML.XMLReader]::Create([IO.StringReader]$xaml) $result = [Windows.Markup.XAMLReader]::Load($reader) foreach($Name in $NamedElement) { $result | Add-Member NoteProperty -Name $Name -Value $result.FindName($Name) -Force } if ($PassThru) { $result } else { $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } } function Show-WPFWindow { param ( [Parameter(Mandatory)] [Windows.Window] $window ) $result = $null $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } #endregion Code Behind #region Convert XAML to Window $window = Convert-XAMLtoWindow -xaml $xaml -NamedElement 'ButCancel', 'ButOk', 'TxtAchternaam', 'TxtAfdeling', 'TxtLocatie', 'TxtMobielnummer', 'TxtTelefoonnummer', 'TxtTitel', 'TxtTussenvoegsel', 'TxtVoornaam' -PassThru #endregion #region Define Event Handlers # Right-Click XAML Text and choose WPF/Attach Events to # add more handlers $window.ButCancel.add_Click( { $window.DialogResult = $false } ) $window.ButOk.add_Click( { $window.DialogResult = $true } ) #endregion Event Handlers #region Manipulate Window Content $null = $window.TxtVoornaam.Focus() #endregion # Show Window $result = Show-WPFWindow -window $window #region Process results '-------------------------------------------------' | Out-File $log -Append " Processing started on $date" | Out-File -FilePath $log -Append "[INFO]`t User $currentuser started the creation of a new account with the following information" | Out-File -FilePath $log -Append if ($result -eq $true) { Add-MWUser -Voornaam $window.TxtVoornaam.Text -Tussenvoegsel $window.TxtTussenvoegsel.Text -Achternaam $window.TxtAchternaam.Text -Locatie $window.TxtLocatie.Text -Titel $window.TxtTitel.Text -Telefoonnummer $window.TxtTelefoonnummer.Text -mobielnummer $window.TxtMobielnummer.Text -Afdeling $window.TxtAfdeling.Text } else { 'User aborted dialog.' | Out-File -FilePath $log -Append } #endregion Process results |
z3fl9e