Create Azure AD B2C local account user with Powershell New-AzureADUser - powershell

I'm trying to create a local user in an Azure AD B2C directory which can be used for authentication immediately after creation.
Connect-AzureAD -TenantId $targetB2cTenant
$passwordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$passwordProfile.Password = "Test-User-Password-Here"
$userName = "TestUser#MyTestB2CTenant.onmicrosoft.com"
$signInNames = #(
(New-Object `
Microsoft.Open.AzureAD.Model.SignInName `
-Property #{Type = "userName"; Value = $userName})
)
$newUser = New-AzureADUser -AccountEnabled $True -DisplayName "testpowershellusercreation" -PasswordProfile $passwordProfile -SignInNames $signInNames -CreationType "LocalAccount"
Disconnect-AzureAD
From reading the documentation I need to specify the CreationType parameter as "LocalAccount":
https://learn.microsoft.com/en-us/powershell/module/azuread/new-azureaduser?view=azureadps-2.0
Creating a B2C user with MFA that can immediately login
However when I run the powershell code I receive the following error:
New-AzureADUser : Error occurred while executing NewUser
Code: Request_BadRequest
Message: One or more properties contains invalid values.
This error message is not present when I remove the -CreationType parameter.
What is the correct way to create a local account in a B2C directory using Powershell?

A sign-in name of type "userName" can't contain the '#' character in the value property.
i.e. You can't set it to an email address.
You might want to also set the following parameters for the new user:
$passwordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$passwordProfile.ForceChangePasswordNextLogin = $False
$passwordProfile.Password = "<Password>"
$newUser = New-AzureADUser ... -PasswordPolicies "DisablePasswordExpiration"

I think you could also change the type of sign-in name from "userName" to "email", to work around this issue and allow users to continue using their foreign domain email addresses as login, if required.
$signInNames = (
(New-Object `
Microsoft.Open.AzureAD.Model.SignInName `
-Property #{Type = "email"; Value = "pstesta#fsdfsd.com"})
)

Related

Powershell - Azure AD : User creation - PasswordProfile error message

I am doing some tests to manage Azure AD users and groups with Powershell.
Unfortunately, i have an issue when i try to create an user. Here my code :
#Specifies the user's password profile.
$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "xxxx"
#Create a AzureAD user account
PS C:\Windows\system32> New-AzureADUser -DisplayName "Power SHELL"
-GivenName "Power" -SurName "SHELL"
-UserPrincipalName power.shell#xxxx.xx -UsageLocation FR
-MailNickName Power Shell -PasswordProfile $PasswordProfile
-AccountEnabled $true
When I validate the PasswordProfile, I have this error message :
New-AzureADUser: Failed to bind parameter 'PasswordProfile'. Cannot convert value '$PasswordProfile' of type 'System.String to type “Microsoft.Open.AzureAD.Model.PasswordProfile”.
I look in a lot of forum but i can't find any solution to make it works.
Thanks for your help.
Geoffrey
I could create the user successfully with the commands you have provided and as per microsoftDocs:
Result:
I could reproduce the issue with error:
Cannot bind parameter 'PasswordProfile'.
" value of type "System.String" to type "Microsoft.Open.AzureAD.Model.PasswordProfile".
when i actually placed quotes around $PasswordProfile like below
New-AzureADUser -DisplayName "xxx" -GivenName "xx" -SurName "xx" -UserPrincipalName xxxx.onmicrosoft.com -UsageLocation US -MailNickName navy -PasswordProfile "$PasswordProfile" -AccountEnabled $true
So please try by placing $PasswordProfile in quotes in your case to resolve the issue.
-PasswordProfile "$PasswordProfile"
similar case here : Cannot convert 'System.Object[]' to the type .. | techcommunity.microsoft.com
Please make sure password is valid and check if string as input type for Parameter somehting like here
or
Try this way:
$PasswordProfile = New-Object -TypeName
Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "Ixxxxxxxk"
$params = #{
AccountEnabled = $true
DisplayName = "xxxn"
PasswordProfile = $PasswordProfile
UserPrincipalName = "xxx#xxxxxx.onmicrosoft.com"
MailNickName = "xxxxx"
}
New-AzureADUser #params
References:
set-azureaduserlicense-cannot-bind-parameter-assignedlicenses

Cannot set credentials with New-Service; have to use sc.exe config – why?

I'm working on a PowerShell script that's …
creating a local user
adding that user to the "Log-in as Service" policy
creating a new service that's supposed to run as the user that's been created in the previous step
When the script first creates the service using New-Service with default credentials and then changes the service's credentials using 'sc.exe', everything runs fine.
But when I try to provide the same credentials right in the call to New-Service, that call fails with exception: "Cannot create service. Reason: Improper user name or password."
What am I doing wrong?
Here's the existing code that's working
New-Service -Name $service.ServiceName -DisplayName $service.DisplayName -BinaryPathName "$binaryFolder" -StartupType Manual > $null
$scOutputText = & sc.exe config $service.ServiceName obj=".\$($userAccount.Username)" password="$($userAccount.Password)" | Out-String
Here's my code that's not working
$params = #{
Name = $service.ServiceName
DisplayName = $service.DisplayName
BinaryPathName = "$binaryFolder"
StartupType = 'Manual'
Credential = (New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList $userAccount.Username, (ConvertTo-SecureString $userAccount.Password -AsPlainText -Force))
}
New-Service #params

Powershell: Set-PnPListItem remove taxonomy value (empty value)[SharePoint Online]

I build a script to map some old taxonomy value from old columns to new columns and tax. values. There are some cases where I have to remove or empty current meta data. Does someone know how it works with Set-PnPListItem. While updating I pass the list item and a hash #{field=value}. Updating works fine but can't remove or empty.
To remove or empty I tried to set the value to -1, $null and "" but nothing works and I will get this error: Set-PnPListItem : Value cannot be null.
Error message
Here is my test result.
#region Variables
$Username = "admin#xxx.onmicrosoft.com"
$Password = "Password"
$siteURL = "https://xxx.sharepoint.com/sites/lee"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials
Set-PnPListItem -List "ListMetaData" -Identity 1 -Values #{"Title" = "TitleUPDATE";"MMField"=$null}
Write-Host "-----------"
Make sure the field is not set as required as Mike suggested.

PowerShell - How do I add a User to an AD User Group using ADSI and alternate credentials

I need to add a user to an AD Group using specific credentials and cannot figure this out.... Here's what I have so far which gives me an "unspecified error" retrieving member 'Add'. Must be done using ADSI as the AD module won't work in my scenario.
$CredsUserName = 'domain\user'
$CredsPassword = 'password'
$GroupPath = "LDAP://CN=<UserGroup>...."
$UserPath = "LDAP://CN=<UserDN>...."
$Group = [ADSI]$GroupPath
$User = [ADSI]$UserPath
$GroupArgs = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $Group, "$CredsUserName", "$CredsPassword"
$GroupArgs.Add($User.adspath)
Try this:
$CredsUserName = 'domain\user'
$CredsPassword = 'password'
$Domain = "<FQDN of the AD domain>/"
$GroupPath = "CN=<UserGroup>...."
$UserPath = "CN=<UserDN>...."
$Group = [adsi]::new("LDAP://$($Domain)$($GroupPath)",$CredsUserName,$CredsPassword)
$Group.member.Add($UserPath)
$Group.CommitChanges()
You only need $Domain if the computer you are using isn't part of the AD domain that contains the group.
Regards,
Stuart.

How to connect Azure Paas Database using Powershell with intergrated security

How can I connect to an Azure SQLDatabase (Paas Instance) using Powershell without a username & password but rather with Active Directory. I can connect with a username and password when I use invoke-sqlcmd as below
$Servername = "XXXXXX.database.windows.net"
$params = #{
Database = $databasename
ServerInstance = $ServerName
Username = $UserName
Password = $password
'OutputSqlErrors' = $true
Query = $QueryString
}
Invoke-Sqlcmd #params
I need the ability to do it with Active Directory. I have read a few articles on how to connect with active directory as long as you specify it on the connection string (Context of C#) Using ODBC connection or other data sources. Since Powershell is based on .Net; this should be do-able..
$ConnString = "DRIVER=ODBC Driver 13 for SQL Server;SERVER=xxxxx.database.windows.net;DATABASE=DBName;Trusted_Connection=Yes"
$Conn = new-object System.Data.Odbc.OdbcConnection($ConnString)
$conn.open()
$cmd = new-object System.Data.Odbc.OdbcCommand("select getdate() as X", $Conn)
$data = new-object System.Data.Odbc.OdbcDataAdapter($cmd)
$dt = new-object System.Data.DataColumn
$data.Fill($dt)
$Conn.Close()
#`server=Server;database=Database;Authentication=ActiveDirectoryIntegrated;`
The objective of trying to use Active Directory is that, within Paas, only AD Accounts can Add other AD accounts. I want to be able to add other accounts with method rather than logging in the Azure portal and adding an AD account manually.
You could use Azure AD account to login Azure SQL database(Paas) by using Azure Active Directory Authentication. More information please refer to this link.
Note: Local domian AD user does not support this.
You could use following script to login with Azure AD authentication.
#You admin Azure AD user name
$Username = "shuitest#*****.onmicrosoft.com"
$Password = "********"
$Database = "testg"
$Server = 'test.database.windows.net'
$Port = 1433
$cxnString = "Server=tcp:$Server,$Port;Database=$Database;Authentication=Active Directory Password;UID=$UserName;PWD=$Password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
$query = "select count(*) from dbo.Authors"
$cxn = New-Object System.Data.SqlClient.SqlConnection($cxnString)
$cxn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($query, $cxn)
$cmd.CommandTimeout = 120
$cmd.ExecuteNonQuery()
$cxn.Close()
The following sample shows how to invoke Add-AzureAccount without the popup dialog:
$username = "someorgid#orgaccount.com"
$password = "Pa$$w0rd" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Add-AzureAccount -Credential $credential
AAD does not / can not parse Kerbs tokens. In order to get integrated auth to work from your desktop, you need to have ADFS (or similar) in your environment. That way your desktop will authenticate against AAD, redirect to ADFS, and your kerbs token will be recognized.
See https://learn.microsoft.com/en-us/azure/sql-database/sql-database-aad-authentication for more information.
this now works for me in the connection string instead of user and pass
Authentication=Active Directory Integrated;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;
Depending on your query you might have to use $cmd.ExecuteScalar() instead of $cmd.ExecuteNonQuery() for example
$query = 'select ##version'
$cxn = New-Object System.Data.SqlClient.SqlConnection($cxnString)
$cxn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($query, $cxn)
$cmd.CommandTimeout = 120
$cmd.ExecuteScalar()
$cxn.Close()