I created a function for creating a new user in AD, assigning an o360 license and enabling mailbox, however, my code is very chaotic and I do not have a much experience with PowerShell. Could you please advise on any improvements, code optimization or generally what could be done better?
Function CreateUser{
#$GroupsAvalible = @(Get-ADGroup -Filter 'GroupCategory -eq "Security" -and GroupScope -ne "DomainLocal"') #| Select-Object Name)
#Show-Menu $GroupsAvalible.name -MultiSelect
Clear-Host
$searchbase = 'OU=Company Users,OU=Company,DC=company,DC=local'
$OuList = @(Get-ADOrganizationalUnit -SearchBase $searchbase -SearchScope Subtree -Filter * | Select-Object Name)
#$GroupsAvalible = @(Get-ADGroup -Filter 'GroupCategory -eq "Security" -and GroupScope -ne "DomainLocal"' | Select-Object Name)
Add-Type -AssemblyName 'System.Web'
$password = [System.Web.Security.Membership]::GeneratePassword(14,8)
$fname = Read-Host -Prompt 'First Name'
$lname = Read-Host -Prompt 'Last Name'
$flname = $fname.Substring(0,1) + $lname
#$cn = $fname + " " + $lname
$ext = Read-Host -Prompt ‘Ext Number’
if ([string]::IsNullOrWhiteSpace($ext)){$ext = ‘0000’}
$email = $flname + '@company.com'
if(($email = Read-Host "Email is set to: $email Press Enter to accept or type new") -eq ''){$email = $flname + '@company.com'}#else{$email}
Clear-Host
'Select OU to put user in'
$OU = Show-Menu($OuList.Name)
$test = "OU=$OU,$searchbase"
Clear-Host
New-ADUser -Name "$fname $lname" -OtherAttributes @{'homeDirectory'="\\company-storage\Users\$flname";'homeDrive'='L';'ipPhone'=$ext} -Path $test -SamAccountName $flname -UserPrincipalName ($fname.Substring(0,1) + $lname + "@company.com") -AccountPassword (ConvertTo-SecureString -String $password -AsPlainText -Force) -ChangePasswordAtLogon $true -Enabled $true
$confirmation = Read-Host "Would you like to copy groups from other user in same OU? Y/N"
if ($confirmation -eq 'Y') {
$UserToCopy = Get-ADUser -Filter * -SearchBase $test
$UserToCopy2 = Show-Menu($UserToCopy.SamAccountName)
Get-ADUser -Identity $UserToCopy2 -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $flname
}
#Assignin Licensces!!!!!!!!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$Usrnm = $env:UserName
$usrnmat = $Usrnm + "@company.com"
$password=Read-Host "Enter administrator password for $usrnmat" -AsSecureString
$cred=New-Object System.Management.Automation.PSCredential($Usrnm,$password)
$cred2=New-Object System.Management.Automation.PSCredential($usrnmat,$password)
$upn = $email
"connecting to Azure...:";Connect-MsolService -Credential $Cred2;"Ok"
"Connecting to DC04...";$s = New-PSSession -ComputerName DC-DC04 -credential $cred;"Ok"
Invoke-Command -Session $s -Scriptblock {
"Importing ADSync Module...";Import-Module -Name "c:\Program Files\Microsoft Azure AD Sync\Bin\ADSync\ADSync.psd1";"Ok"
"Forcing Azure Sync...";Start-ADSyncSyncCycle -PolicyType Delta;"Ok"}
Do{$User = Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue
Start-Sleep 1
Clear-Host
"Waiting for $upn to sync to Azure"
} Until($Null -ne $user)
write-host "$user Synced"
"Closing Connection with DC04...";Remove-PSSession $s; "Ok"
"Setting user UsageLocation to GB..."; Set-MsolUser -UserPrincipalName $upn -UsageLocation GB ; "Ok"
$chs = Show-Menu -MenuItems ("Bussines","E3")
if ($chs -eq "Bussines"){$License = "company:O365_BUSINESS_PREMIUM"}
if ($chs -eq "E3"){$License = "company:ENTERPRISEPACK"}
#Get-MsolUser -All -UnlicensedUsersOnly
$EnabledPlans = @(
'TEAMS1'
'O365_BUSINESS'
'OFFICESUBSCRIPTION'
)
$AllPlans = (Get-MsolAccountSku | Where-Object { $_.AccountSkuId -eq $License } | Select-Object -ExpandProperty ServiceStatus).ServicePlan.ServiceName
$DisabledPlans = $AllPlans | Where-Object { $EnabledPlans -notcontains $_ }
$E1CustomizedLicense = New-MsolLicenseOptions -AccountSkuId $License -DisabledPlans $DisabledPlans
Set-MsolUserLicense -UserPrincipalName $upn -AddLicenses $License -LicenseOptions $E1CustomizedLicense
#Setting Up MailBox!!!!!<<<<<<<<<<<<<<<<<<<<<<<<<
Get-PSSession | Remove-PSSession
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://company-exchange1/powershell/ -Authentication Kerberos -AllowRedirection
Import-PSSession $Session –DisableNameChecking -AllowClobber
Clear-Host
Write-Host "This fucker thinks MB is bigger than GB so automation is impossible, select DB with biggest free space..." -ForegroundColor Red
Get-MailboxDatabase -Status | Where-Object {$_.Identity -notlike "company-Archive*"} | Select-Object name,AvailableNewMailboxSpace
$db1 = Get-MailboxDatabase | Where-Object {$_.Identity -notlike "company-Archive*"}# | Select AvailableNewMailboxSpace | Sort AvailableNewMailboxSpace -Descending
$db1 = Show-Menu -MenuItems ($db1)
$db = Get-MailboxDatabase | Where-Object {$_.Identity -eq $db1} | select-object name
$ach1 = $db1 -replace "Database", "Archive"
$ach = Get-MailboxDatabase | Where-Object {$_.Identity -eq $ach1} | select-object name
$ach.name
$db.name
Enable-Mailbox -database $db.name -Identity $flname -Alias $flname
pause
Get-PSSession | Remove-PSSession
")}