Есть ли способ оптимизировать этот скрипт, чтобы он работал более эффективно? - PullRequest
0 голосов
/ 23 апреля 2019

Я написал сценарий, который создает нового пользователя 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 голосов
/ 30 апреля 2019

Мне пришлось создать 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

Надеюсь, пользователи найдут это полезным

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...