Мне пришлось создать 2 части к этому сценарию.Первая часть создала пользователя и почтовый ящик, затем вторая часть лицензировала пользователя в Office 365, но я подождал не менее 30 минут, прежде чем запустить вторую часть.
Часть 1
CLS
Import-Module ActiveDirectory
function CreateADUser
{
#Install the module that will let us to perform certain tasks in Excel
#Install PSExcel Module for powershell
if (Get-Module -ListAvailable -Name ImportExcel)
{
#Write-Host "Module exists"
}
else
{
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name ImportExcel -Force
}
Import-Module ImportExcel
<#
The worksheet variable will need to be modified before running this script.
Whatever the name of the worksheetis that you want to import data from, type that in below.
#>
$worksheet = "Sheet1"
#Remove the emails file if it already exists
$EmailFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\emails.txt"
if([System.IO.File]::Exists($EmailFile))
{
remove-item $EmailFile -Force
}
#The file we will be reading from
$ExcelFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\NW Master.xlsx"
#This will be where we write errors to
$ErrorFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\ERROR.txt"
$Import = Import-Excel -Path $ExcelFile -WorkSheetname $worksheet -StartRow 1
#Grab all the information for each individual user and store it in an array. (start with row 1, because that's where user information is listed)
foreach ($User in $Import)
{
#Get Display name
$DisplayName = $User."Full Name"
#Get First Name
$FirstName = $User."First Name"
#Get Last Name
$LastName = $User."Last"
#Username
$Username = ($FirstName[0] + $LastName)
#If Username has any spaces, then remove the space
if($Username -like "* *")
{
$Username = $Username -replace " ",""
}
#Set new aduser password
$UserPassword = "Password123!@#"
$OfficeLocation = $user."Office Location"
#The profile we are copying from
$CopiedProfile = $($User."Modeled Profile")
$CopiedProfileUser = Get-ADUser -Filter 'DisplayName -eq $CopiedProfile' -Properties *
#Check to see if the new account we're going to create already exists
$validate = Get-ADUser -Filter 'DisplayName -eq $DisplayName'
#If($validate -eq $Null)
If($Null -eq $validate)
{
#Email Address
$Email = $Username+"@domain.com"
#We will output the emails to a file. We will need that for a later time
$Email | Out-File -Append -FilePath $EmailFile
Try
{
#User does not exist in AD, create the account
$userprops=@{
Name=$DisplayName
SamAccountName=$Username
Surname=$LastName
GivenName=$FirstName
DisplayName=$DisplayName
Department=$CopiedProfileUser.Department
Description=$CopiedProfileUser.Description
EmployeeNumber=$CopiedProfileUser.employeeNumber
EmployeeID=$CopiedProfileUser.employeeID
Office=$CopiedProfileUser.physicalDeliveryOfficeName
City=$CopiedProfileUser.City
l=$CopiedProfileUser.l
Manager=$CopiedProfileUser.Manager
State=$CopiedProfileUser.st
StreetAddress=$CopiedProfileUser.streetAddress
Company=$CopiedProfileUser.company
PostalCode=$CopiedProfileUser.PostalCode
Title=$CopiedProfileUser.Title
UserPrincipalName=$Email
Path=$CopiedProfileUser.DistinguishedName -replace '^cn=.+?(?<!\\),'
AccountPassword=ConvertTo-SecureString -String $UserPassword -AsPlainText -Force
Enabled=$True
}
New-ADUser @userprops
#Add the user group memberships from the copied profile
$CopiedProfileUser.memberof | add-adgroupmember -members $Username -ErrorAction SilentlyContinue
#Add to the Dynamic Distribution attribute and other AD attributes
Set-ADUser -Identity $Username -Replace @{ extensionAttribute2 = "DynamicDistro"; co = "USA"; physicalDeliveryOfficeName = $OfficeLocation }
}
Catch
{
$_.Exception.Message | Out-File -Append -FilePath $ErrorFile
$_.Exception.ItemName | Out-File -Append -FilePath $ErrorFile
$_.InvocationInfo.MyCommand.Name | Out-File -Append -FilePath $ErrorFile
$_.ErrorDetails.Message | Out-File -Append -FilePath $ErrorFile
$_.InvocationInfo.PositionMessage | Out-File -Append -FilePath $ErrorFile
$_.CategoryInfo.ToString() | Out-File -Append -FilePath $ErrorFile
$_.FullyQualifiedErrorId | Out-File -Append -FilePath $ErrorFile
}
}
Else
{
#If the username exists, use the first 2 characters of their first name
$UsernameModified = (($FirstName.Substring(0,2))+$LastName)
#If UsernameModified has any spaces, then remove the space
if($UsernameModified -like "* *")
{
$UsernameModified = $UsernameModified -replace " ",""
}
#Email Address
$EmailModified = $UsernameModified+"@domain.com"
#We will output the emails to a file. We will need that for a later time
$EmailModified | Out-File -Append -FilePath $EmailFile
#User already exists, so lets get some info
Write-output "User $Username Full Name: $DisplayName already exists in AD: " $validate | Out-File -Append -FilePath $ErrorFile
$userprops=@{
Name=$DisplayName
SamAccountName=$UsernameModified
Surname=$LastName
GivenName=$FirstName
DisplayName=$DisplayName
Department=$CopiedProfileUser.Department
Description=$CopiedProfileUser.Description
EmployeeNumber=$CopiedProfileUser.employeeNumber
EmployeeID=$CopiedProfileUser.employeeID
Office=$CopiedProfileUser.physicalDeliveryOfficeName
City=$CopiedProfileUser.City
l=$CopiedProfileUser.l
Manager=$CopiedProfileUser.Manager
State=$CopiedProfileUser.st
StreetAddress=$CopiedProfileUser.streetAddress
Company=$CopiedProfileUser.company
PostalCode=$CopiedProfileUser.PostalCode
Title=$CopiedProfileUser.Title
UserPrincipalName=$EmailModified
Path=$CopiedProfileUser.DistinguishedName -replace '^cn=.+?(?<!\\),'
AccountPassword=ConvertTo-SecureString -String $UserPassword -AsPlainText -Force
Enabled=$True
}
New-ADUser @userprops
#Add the user group memberships from the copied profile
$CopiedProfileUser.memberof | add-adgroupmember -members $UsernameModified -ErrorAction SilentlyContinue
#Add to the Dynamic Distribution attribute and other AD attributes
Set-ADUser -Identity $UsernameModified -Replace @{ extensionAttribute2 = "DynamicDistro"; co = "USA"; physicalDeliveryOfficeName = $OfficeLocation }
}
}
}
Function CreateMailBox
{
#Import the sync module we will need
#Check if we have a session open right now
$SessionsRunning = get-pssession
if($SessionsRunning.ComputerName -like "*aad-sync-srvr*")
{
#If session is running we don't need to do anything
}
else
{
#If session isn't running, lets start it
$AADsession = New-PSSession -ComputerName "aad-sync-srvr.domain.com"
Invoke-Command -Session $AADsession -ScriptBlock {Import-Module -Name 'ADSync'}
}
#Sync our changes with AD
Invoke-Command -Session $AADsession -ScriptBlock {Start-ADSyncSyncCycle -PolicyType Delta}
#Sleep for a minute to make sure the sync finishes
Start-Sleep -s 60
if($SessionsRunning.ComputerName -like "*mbx-srvr*")
{
#If session is running we don't need to do anything
}
else
{
#If session isn't running, lets start it
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mbx-srvr.domain.com/PowerShell/ -Authentication Kerberos
Import-PSSession $Session
}
#Now lets read the emails from the emails.txt file and create the mailboxes for the new users
$EmailFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\emails.txt"
Get-Content $EmailFile | ForEach-Object {
$useremail = $_
$userprefix = ($useremail -split "@")[0]
$mos = $userprefix + "@domain.mail.onmicrosoft.com"
Enable-RemoteMailbox $userprefix -RemoteRoutingAddress $mos
}
#Sleep for a minute to make sure the sync finishes
Start-Sleep -s 60
#Run the sync once more
Invoke-Command -Session $AADsession -ScriptBlock {Start-ADSyncSyncCycle -PolicyType Delta}
# Remove-PSSession $Session
Remove-PSSession $AADsession
}
#Create the new user
CreateADUser
#Create the mailbox
CreateMailBox
Часть 2
CLS
Function LicenseOfficeUser
{
if (Get-Module -ListAvailable -Name MSOnline)
{
#Write-Host "Module exists"
}
else
{
Install-Module -Name MSOnline -Force
}
#Quick way to see if we are connected to the MSOL service is to run a simple query. If it doesn't return NULL, then we are fine and don't need to load it again
if(!(Get-MsolUser -SearchString "Some AD User" -ErrorAction SilentlyContinue))
{
$creds = Get-Credential
Connect-MsolService -Credential $creds
}
$EmailFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\emails.txt"
$license = (Get-MsolAccountSku).AccountSkuId | Where-Object {$_ -like "domain:ENTERPRISEPACK" }
#Now lets read the emails from the emails.txt file and create the mailboxes for the new users
Get-Content $EmailFile | ForEach-Object {
$useremail = $_
$LicenseOptions = New-MsolLicenseOptions -AccountSkuID $license
Set-MsolUser -UserPrincipalName $useremail -UsageLocation 'US' -ErrorAction SilentlyContinue
Set-MsolUserLicense -UserPrincipalName $useremail -AddLicenses $license -LicenseOptions $LicenseOptions -ErrorAction SilentlyContinue
}
}
#License the User in Office
LicenseOfficeUser
Надеюсь, пользователи найдут это полезным