Automate Connect-AzureAD Powershell - powershell

I created a script using powershell that connect to AzureAD and it was working fine using the following:
Connect-AzureAD -TenantId $TenantId
The sign in window pops up and I am able to successfully connect. However, I need to setup the script to run automatically so I found this code to do it:
# Set Configs
$TenantId = "<tenant id>"
$AzureUser = "<user>"
$AzurePass = Get-Content "cred.txt" | ConvertTo-SecureString
# Connect to Azure AD
$AzureCred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $AzureUser, $AzurePass
Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
But I can't seem to get it to work. I use the following to generate my cred.txt file:
Read-Host -assecurestring | convertfrom-securestring | out-file C:\cred.txt
When I run it, I get the following error:
Connect-AzureAD : One or more errors occurred.: The character set
provided in ContentType is invalid. Cannot read content as string
using an invalid character set. At line:9 char:1
+ Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : One or more errors occurred. At line:9 char:1
+ Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AggregateException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : The character set provided in ContentType is
invalid. Cannot read content as string using an invalid character set.
At line:9 char:1
+ Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], InvalidOperationException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : '"utf-8"' is not a supported encoding name. For
information on defining a custom encoding, see the documentation for
the Encoding.RegisterProvider method. Parameter name: name At line:9
char:1
+ Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], ArgumentException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : One or more errors occurred.: The character set
provided in ContentType is invalid. Cannot read content as string
using an invalid character set. At line:9 char:1
+ Connect-AzureAD -TenantId $TenantId -Credential $AzureCred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-AzureAD], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Open.Azure.AD.CommonLibrary.AadAuthenticationFailedException,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
I logged in on a different tenant using the same script and it was working fine. It is just not working to the tenant that has federation on. Any workaround for this aside from turning off federation?

Related

PowerShell remoting to execute Windows update

I need to modify the below script to execute the Windows Update so it downloads and updates the remote server:
Invoke-RemoteExecution($computername){
$cred = get-credential
invoke-command -computername $computername -Credential $cred -scriptblock {
Function Search-Updates
{
$Criteria = "IsInstalled=0 and Type='Software'"
#Search for relevant updates.
$Searcher = New-Object -ComObject Microsoft.Update.Searcher
$SearchResult = $Searcher.Search($Criteria).Updates
return [System.MarshalByRefObject]$SearchResult
}
Function Download-Updates
{
Param ($SearchResult)
$Session = New-Object -ComObject Microsoft.Update.Session
$Downloader = $Session.CreateUpdateDownloader()
$Downloader.Updates = $SearchResult
$Downloader.Download()
}
[System.MarshalByRefObject]$SearchResult = Search-Updates
Download-Updates -SearchResult $SearchResult
}
}
Invoke-RemoteExecution -computername yourcomputername
The error I am facing is like the below:
Invoke-RemoteExecution -computername PRD-SVR01-VM
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : PRD-SVR01-VM
The property 'Updates' cannot be found on this object. Verify that the property exists and can be set.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
+ PSComputerName : PRD-SVR01-VM
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : PRD-SVR01-VM
I have tried to use the remoting but it is still failed as above.

Creating user policy Powershell MicrosoftTeams session error

When I try to create a user policy for my active directory I get this error:
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:22959 char:38
+ ... -Session (Get-PSImplicitRemotingSession -CommandName 'New-CsApplic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code that I'm using is this:
Import-Module MicrosoftTeams
# Get the credentials
$password = ConvertTo-SecureString -AsPlainText -Force -String "password"
$credentials = New-Object System.Management.Automation.PsCredential("email", $password)
# Connect to Microsoft Teams
Connect-MicrosoftTeams -Credential $credentials
New-CsApplicationAccessPolicy -Identity Random -AppIds "appid" -Description "Users"
Grant-CsApplicationAccessPolicy -PolicyName Random -Identity "userObjectId"
I know that the command New-CsApplicationAccessPolicy is creating the error but my guess is that it's caused by the command Connect-MicrosoftTeams because from what I can understand is that Connect-MicrosoftTeams creates a session.
Is there a way to set the session via a parameter or is this something you need to do outside this method?

Azure commands not working in ISE but do in PS shell

I am trying to connect to my Azure AD with my companies O365 account. When I run the commands in the PS shell, works great. But trying to make a ps1 script file, commands fail in ISE. Code and errors below:
Code:
$managedcred = get-storedcredential -Target o365
connect-azuread -credential $managedcred
Error:
Connect-AzureAD : One or more errors occurred.: AADSTS50126: Invalid username or password.
Trace ID: 3bbf3cba-61c3-45c5-a19f-60973b7c2700
Correlation ID: 14599060-8bb3-4fce-afda-621efc3660ed
Timestamp: 2019-10-03 16:05:03Z
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : One or more errors occurred.
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AggregateException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : AADSTS50126: Invalid username or password.
Trace ID: 3bbf3cba-61c3-45c5-a19f-60973b7c2700
Correlation ID: 14599060-8bb3-4fce-afda-621efc3660ed
Timestamp: 2019-10-03 16:05:03Z
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AdalServiceException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : Response status code does not indicate success: 400 (BadRequest).
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], HttpRequestException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : {"error":"invalid_grant","error_description":"AADSTS50126: Invalid username or password.\r\nTrace ID:
3bbf3cba-61c3-45c5-a19f-60973b7c2700\r\nCorrelation ID: 14599060-8bb3-4fce-afda-621efc3660ed\r\nTimestamp: 2019-10-03
16:05:03Z","error_codes":[50126],"timestamp":"2019-10-03 16:05:03Z","trace_id":"3bbf3cba-61c3-45c5-a19f-60973b7c2700","correlation_id":"14599060-8bb3-4fce-afda-621efc366
0ed","error_uri":"https://login.microsoftonline.com/error?code=50126"}: Unknown error
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AdalException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Connect-AzureAD : One or more errors occurred.: AADSTS50126: Invalid username or password.
Trace ID: 3bbf3cba-61c3-45c5-a19f-60973b7c2700
Correlation ID: 14599060-8bb3-4fce-afda-621efc3660ed
Timestamp: 2019-10-03 16:05:03Z
At line:1 char:1
+ Connect-AzureAD -Credential $managedcred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-AzureAD], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Open.Azure.AD.CommonLibrary.AadAuthenticationFailedException,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
So it appears that the first command works fine, but the connect fails.
According to error message, you do not use the correct username and password to connect Azure AD. Please use the following command to check it.
Get-StoredCredential -Target O365 -AsCredentialObject
Besides, according to my understanding, you want to connect Azure AD without a prompt. You also can use the following command:
$name = ""
$password = ""
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($name, $secpasswd)
Connect-AzureAD -Credential $mycreds
Update
According to research, app password is used to complete MFA with the clients which do not support modern authentication, such as outlook. For more details, please refer to https://support.microsoft.com/en-au/help/12409/microsoft-account-app-passwords-and-two-step-verification. So we cannot use app password to connect Azure AD in PowerShell ISE.
According to the situation, I suggest you use service principal to connect Azure AD. For more details, please refer to https://learn.microsoft.com/en-us/powershell/azure/active-directory/signing-in-service-principal?view=azureadps-2.0.

Not able to initialize Namespace Manager in Powershell

When I am initializing the Namespace manager, I am getting an error message that the constructor was not found.
I am trying to run $XmlNSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable and received below error:
New-Object : A constructor was not found. Cannot find an appropriate constructor for type System.Xml.XmlNamespaceManager.
At line:1 char:17
+ ... NSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
$XmlNSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable

connecting to sharepoint oniline using Powershell : Cannot find an appropriate constructor for type Microsoft.SharePoint.Client.ClientContext

Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll