0

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 "abc@test123.co.uk" -To "abcHelpdesk@test123.co.uk" -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

S3RRATED
  • 3
  • 1

1 Answers1

0

A couple of thoughts:

  • Try using Start-Sleep rather than Start-Countdown
  • If it isn't asynchronous, you can try running 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 completed
  • If you have the e-mail address, then you can use a while 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

}
Anthony Norwood
  • 357
  • 1
  • 7
  • Thanks for the quick reply, I think I worked it out - pretty sure it was the start of my script has a function that is called 'Start-Countdown' for a progress bar and it was just starting the AD Sync but then immediately pausing it. -AsJob on the ADsync sorted it Thanks :) – S3RRATED Feb 07 '23 at 16:01