" Import-Csv "C:\U" /> " Import-Csv "C:\U" /> " Import-Csv "C:\U"/>

How to pass MFA enabled Azure account credentials into PowerShell ScriptBlock?

1.3k Views Asked by At
connect-azuread | out-null

$global:token = [Microsoft.Open.Azure.AD.CommonLibrary.AzureSession]::AccessTokens

$ceo = "<ceo_username>"

Import-Csv "C:\Users\abhilash\Music\users.txt" | ForEach-Object {

$scriptblock = {

param($userprincipalname)

Connect-Azuread -AadAccessToken $global:token.AccessToken.AccessToken -accountid <my_username>

New-Object PSObject -property @{

Manager1 = $l = (Get-AzureADUserManager -ObjectId $userprincipalname).userprincipalname

Manager2 = $m = if ($l -ne $null -and $l -ne $CEO) { (Get-AzureADUserManager -ObjectId $l).userprincipalname } else { $null }

Manager3 = $n = if ($m -ne $null -and $m -ne $CEO) { (Get-AzureADUserManager -ObjectId $m).userprincipalname } else { $null }

Manager4 = $o = if ($n -ne $null -and $n -ne $CEO) { (Get-AzureADUserManager -ObjectId $n).userprincipalname } else { $null }

} | Select @{N='User';E={$userprincipalname}},Manager1,Manager2,manager3,manager4

}

Start-Job $ScriptBlock -ArgumentList $_

}

While (Get-Job -State "Running") { Start-Sleep 10 }

Get-job| receive-job


"You must call the Connect-AzureAD cmdlet before calling any other cmdlets" ...... I get this error even after having active session, tried connecting with accesstoken, now I get error as "Cannot validate argument on parameter 'AadAccessToken'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again."

1

There are 1 best solutions below

1
AjayKumarGhose On

We have tried with your given code and its asking for users to add their credential for authentication.

AFAIK, we can not pass the MFA enabled azure account credential in PowerShell script.

So we have to use the cmdlets to connect our services without using parameter Credential. This will show us the Sign in to our account popup (log-in window)of the services which has the support for MFA as below. We have provide the user account name in ceo and my username. enter image description here

For more information please refer this BLOG & SO THREAD