有没有一种方法可以优化此脚本,使其运行效率更高?

时间:2019-04-23 02:22:20

标签: powershell active-directory azure-active-directory office365

我编写了一个脚本,该脚本创建一个新的Active Directory用户,在混合交换环境中创建一个邮箱,然后为该用户许可Office 365。我的脚本运行良好,但是我试图查看是否有更有效的方法来执行此操作。我遇到的一个问题是,当我创建邮箱并向用户授予许可时,它不断提示我使用我的AD凭据进行“ MSOL-connect”登录...显然,我处于循环状态,但我知道,但是有没有办法只加载一次而不会不断询问我每个用户?

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-Module -Name ImportExcel
    }

    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 = "May"

    #The file we will be reading from
    $ExcelFile = (Split-Path $script:MyInvocation.MyCommand.Path) + "\test.xlsx"

    $Import = Import-Excel -Path $ExcelFile -WorkSheetname $worksheet -StartRow 3

    #Grab all the information for each individual user and store it in an array. (start with row 4, because that's where user information is listed)
    foreach ($User in $Import)
    {
        $DisplayName = $User."Name"

        #Get First Name
        $FirstName = ($User."Name" -split " ")[0]

        #Get Last Name
        $LastName = ($User."Name" -split " ")[1]

        #Get UserName (initial of first name and last name)
        $Username = $FirstName[0]+$LastName

        #Set new aduser password
        $UserPassword = "P@55W0rD!@#"

        #Email Address
        $Email = $Username+"@blah.com"

        #The profile we are copying from
        $CopiedProfile = $($User."Copy Similar To")        
        #$CopiedProfileUser = Get-ADUser -Filter { DisplayName -eq $CopiedProfile } -Properties memberof
        $CopiedProfileUser = Get-ADUser -Filter { DisplayName -eq $CopiedProfile } -Properties *
        #$CopiedProfileUser

        #Check to see if the new account we're going to create already exists
        $validate = Get-ADUser -Filter { sAMAccountName -like $Username }
        #$validate

        If($validate -eq $Null) 
        {
            #User does not exist in AD, create the account

           #Fill in the fields for our new user
            $CopiedProfileUser | ForEach-Object{
                $userprops=@{
                    Name=$DisplayName
                    SamAccountName=$Username
                    Surname=$LastName
                    GivenName=$FirstName
                    DisplayName=$DisplayName
                    Department=$_.Department
                    Description=$_.Description
                    EmployeeNumber=$_.employeeNumber
                    EmployeeID=$_.employeeID
                    Office=$_.physicalDeliveryOfficeName
                    City=$_.City
                    l=$_.l
                    Manager=$_.Manager
                    State=$_.st
                    StreetAddress=$_.streetAddress
                    Company=$_.company
                    PostalCode=$_.PostalCode
                    Title=$_.Title
                    UserPrincipalName=$Email
                    Path=$_.DistinguishedName -replace '^cn=.+?(?<!\\),'
                    AccountPassword=ConvertTo-SecureString -String $UserPassword -AsPlainText -Force
                    Enabled=$_.Enabled
                }
                New-ADUser @userprops
            }
            #$userprops

            $CopiedProfileUser.memberof | add-adgroupmember -members $Username

            #Add to the Dynamic Distribution Group
            Set-ADUser –Identity $Username -Clear "extensionAttribute2"
            Set-ADUser -Identity $Username -Add @{ extensionAttribute2 = "DynamicDistro" }

            Set-ADUser -Identity $Username -Add @{ co = "USA" }
            Set-ADUser -Identity $Username -Add @{ msExchRecipLimit = $CopiedProfileUser.msExchRecipLimit }
            Set-ADUser -Identity $Username -Add @{ msExchUserAccountControl = $CopiedProfileUser.msExchUserAccountControl }
            Set-ADUser -Identity $Username -Add @{ physicalDeliveryOfficeName = $CopiedProfileUser.physicalDeliveryOfficeName }


            ############################################################
            ############################################################
            ############################################################
            ######                                                ###### 
            ######                                                ######
            ######                 Mail Setup                     ######
            ######                                                ######
            ######                                                ######
            ############################################################
            ############################################################
            ############################################################

            #Now we need to setup the mailbox for the new user
            if (Get-Module -ListAvailable -Name ADSync) 
            {
                    #Write-Host "Module exists"
            } 
            else 
            {
                Install-Module -Name ADSync
            }

            #Check if the module is already running, if not, run it.
            If (!(Get-module ADSync)) 
            {
                Import-Module ADSync -ErrorAction SilentlyContinue
            }

            #Use the currently logged in session to authenticate
            $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mailbox-server.mydomain.com/PowerShell/ -Authentication Kerberos
            Import-PSSession $Session

            $mos = $Username + "@blah.mail.onmicrosoft.com"

            #This creates the mailbox
            Enable-RemoteMailbox $Username -RemoteRoutingAddress $mos

            ############################################################
            ############################################################
            ############################################################
            ######                                                ###### 
            ######                                                ######
            ######           License User in Office               ######
            ######                                                ######
            ######                                                ######
            ############################################################
            ############################################################
            ############################################################

            #Connect to the services we will need.
            #Connect-AzureAD
            Connect-MsolService

            Set-MsolUser -UserPrincipalName $email -UsageLocation US
            Set-MsolUserLicense -UserPrincipalName $email -AddLicenses "blah:ENTERPRISEPACK"

            pause
        }
        Else
        {
            #$_.Exception | -filepath (Split-Path $script:MyInvocation.MyCommand.Path) + "\error.xlsx"
            Write-Error "User Account already exists"
        }
    }
}


CreateADUser

1 个答案:

答案 0 :(得分:0)

我必须为此脚本创建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

希望用户觉得这很有用