Kinda new to powershell and trying to write scripts in general. Im trying to create a script that creates an AD user and then assigns that user a license. However doesn't seem to matter what I do, the sync command I have doesnt execute before the waiting period; so it cant find the user to assign the license to. Any ideas what Im getting wrong?
`$DCSync = 'DC01'
#Starts AD Sync
Invoke-Command -ComputerName $DCSync -scriptblock {
Import-Module ADSync
Start-ADSyncSyncCycle -PolicyType Delta
Write-Output "testing"
}
send-mailmessage -From "[email protected]" -To "[email protected]" -Subject "New user creation" -Body "Please connect to DC01 and authenticate to Office 365 to complete the user setup for $UserPrincipalName" -SmtpServer [REDACTED]
Start-Countdown -Seconds 5 -Message "Synchronizing changes to Office 365"
#Install-Module PowerShellGet
#Install-Module Microsoft.Graph -Scope CurrentUser
#Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Connect-MgGraph -Scopes User.ReadWrite.All, Organization.Read.All
$MgUserID = Get-MgUser -UserId "$EmailAddress"
Update-MgUser -UserId "$MgUserID" -UsageLocation GB
Set-MgUserLicense -UserId $MgUserID -AddLicenses @{SkuId = "6fd2c87f-b296-42f0-b197-1e91e994b900" } -RemoveLicenses @()`
Write-Outpost "testing" always prints after the ADsync commands
Creating a user - assigning a license to newly created user It just errors out because its not syncing to AD using the command so the user doesn't 'exist' yet
A couple of thoughts:
Start-Sleep
rather than Start-Countdown
Start-ADSyncSyncCycle -PolicyType Delta
using the -AsJob
parameter, and then retrieve the status of that job using a while
loop and not proceeding until the job is completedwhile
loop to not proceed until the account is created, like:while ($null -eq $MgUserID){
try {
$MgUserID = Get-MgUser -UserId "$EmailAddress"
}
catch {
$MgUserID = $null
}
Start-Sleep -Seconds 30
}