As you can see I have been using multiple conditions such as if
, elseif
, else
, but it takes too much time to complete the process.
How can I improve the speed of the script?
Import-Module ActiveDirectory
Import-Module MSOnline
$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PSCredential ("[email protected]", $password)
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $Livecred
$userID = Import-Csv "c:\export\list.csv"
$LogFile = "C:\export\logs.txt"
foreach ($user in $userID)
{
$ADuser = Get-ADUser -Filter "EmployeeId -eq $($user.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName
$O365User = Get-MsolUser -UserPrincipalName $ADuser.UserPrincipalName
if (($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $true))
{
Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
#move user OU, change description, disable account, remove SG members list
#$Date = Get-Date -Format MM-dd-yyyy
#Set-ADUser -Identity $ADuser.SAMAccountName -Replace @{info="User disabled at $Date"}
# $User has been disabled and remove office 365 licence from user.
#"$ADuser.SAMAccountName has been disabled and remove office 365 licence from user." | Out-File $LogFile -Append -Force
}
elseif (($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $false))
{
#move user OU, change description, disable account, remove SG members list
#Set-ADUser username -Replace @{info='New info for the notes field'}
#"$ADuser.SAMAccountName has been disabled and already without office 365 licence." | Out-File $LogFile -Append -Force
}
elseif (($ADuser.Enabled -eq $false) -and ($O365User.isLicensed -eq $false))
{
#do nothing
#"$ADuser.SAMAccountName has been already disabled and already without office 365 licence." | Out-File $LogFile -Append -Force
}
elseif (($ADuser.Enabled -eq $false) -and ($O365User.isLicensed -eq $true))
{
Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
#"$ADuser.SAMAccountName has been already disabled and but revoke office 365 licence." | Out-File $LogFile -Append -Force
}
else
{
#User does not exist in AD
#"$user.EmployeeID does not exist in Active Directory." | Out-File $LogFile -Append -Force
}
}
Get-*User
) into a Background Job (checkStart-Job
cmdlet) and use a concurrent blocking collection to fetch results from there. You may also try withforeach -Parallel
. I'm not sure which one will perform better. \$\endgroup\$