Azure commands not working in ISE but do in PS shell - powershell

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.

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.

Powershell create access policy Azure

I'm trying to create an access policy so that I can create meetings using Microsoft Graph API on the user's behalf. To do this I need to do a script that is similar to this:
Connect-MicrosoftTeams
New-CsApplicationAccessPolicy -Identity Random -AppIds "applicationid" -Description "Users"
Grant-CsApplicationAccessPolicy -PolicyName Random -Identity "userId"
But when I try to run the second line I get this error:
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:63 char:22
+ $remoteSession = & (Get-CsOnlineSessionCommand)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-CsOnlineSession], UnauthorizedAccessException
+ FullyQualifiedErrorId : UnauthorizedAccessException,Microsoft.Teams.ConfigApi.Cmdlets.GetCsOnlineSession
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
I'm guessing it has something to do with the first command that it's not remembering my login, but I can't find anywhere on how to do this. Does anyone know what I'm doing wrong and what the correct way is?.
Edit:
I finished the first problem. I needed to create an account on the active directory itself because Microsoft accounts weren't allowed. But my second error is still here:
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
Is there a way to set the session via a parameter or is this something you need to do outside this method?

Automate Connect-AzureAD 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?

Invalid namespace in PowerShell working with FSRM

Trying PS command:
Set-FsrmFileGroup -Name "Anti-Ransomware File Groups" -IncludePattern #((Invoke-WebRequest -Uri "https://fsrm.experiant.ca/api/v1/combined" -UseBasicParsing).Content | ConvertFrom-Json | % {$_.filters})
Getting error:
New-FsrmFileGroup : Invalid namespace
At line:1 char:1
+ New-FsrmFileGroup -Name "Anti-Ransomware File Groups" -IncludePattern #((Invoke- ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (MSFT_FSRMFileGroup:Root/Microsoft/...T_FSRMFileGroup) [New-FsrmFileGroup], CimException
+ FullyQualifiedErrorId : HRESULT 0x8004100e,New-FsrmFileGroup
I also notice some errors in FSRM:
Firewall is off and I am domain admin running this as admin. SFC and a WMI repair came back as good. I am going based off a guide (https://fsrm.experiant.ca/). This has worked across a ton of other servers so I don't believe the commands to be improperly formatted.
Output of Get-WmiObject -Namespace 'Root/Microsoft/Windows/Fsrm' -List:
Get-WmiObject : Could not get objects from namespace Root/Microsoft/Windows/Fsrm.
Invalid namespace
At line:1 char:1
+ Get-WmiObject -Namespace 'Root/Microsoft/Windows/Fsrm' -List
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : INVALID_NAMESPACE_IDENTIFIER,Microsoft.PowerShell.Commands.G‌​etWmiObjectCommand

PowerShell Access Denied only for Local user who is also Admin but not for domain user who is local admin

We are trying to setup a machine for PSRemoting using the following command
Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI
for some reason this only works when we open the powershell in the context of a domain user who is a local administrator.
PS C:\Windows\system32> Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI
Confirm
Are you sure you want to perform this action?
Performing operation "Set-PSSessionConfiguration" on Target "Name:
Microsoft.PowerShell".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):A
Access is denied.
At line:15 char:26
+ if ((!$pluginName) -or <<<< !(test-path "$pluginDir"))
+ CategoryInfo : InvalidOperation: (:) [], InvalidOperationExcept
ion
+ FullyQualifiedErrorId : WsManError
Join-Path : Access is denied.
At line:22 char:35
+ $pluginFileNamePath = Join-Path <<<< "$pluginDir" 'FileName'
+ CategoryInfo : NotSpecified: (:) [Join-Path], InvalidOperationE
xception
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Power
Shell.Commands.JoinPathCommand
Test-Path : Cannot bind argument to parameter 'Path' because it is an empty str
ing.
At line:23 char:19
+ if (!(test-path <<<< "$pluginFileNamePath"))
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingVa
lidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
lowed,Microsoft.PowerShell.Commands.TestPathCommand
Get-Item : Cannot bind argument to parameter 'LiteralPath' because it is an emp
ty string.
At line:29 char:43
+ $pluginFileName = get-item -literalpath <<<< "$pluginFileNamePath"
+ CategoryInfo : InvalidData: (:) [Get-Item], ParameterBindingVal
idationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
lowed,Microsoft.PowerShell.Commands.GetItemCommand
Set-PSSessionConfiguration : Session Configuration "Microsoft.PowerShell" is no
t a PowerShell based shell.
At line:89 char:27
+ Set-PSSessionConfiguration <<<< $args[0] $args[1] $args[2] $args[3] $args[4]
$args[5] $args[6] $args[7] $args[8]
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,Set-PSSessionConfiguration
PS C:\Windows\system32>
it looks to me that there is something that is preventing access to the wsman:\localhost\plugin but can't understand how that can be fixed. This only happens in our test bed, but in our development environment we have no such issues.
Does any one have any clue as to what additional user access is for this command to work that an local administrator user may not have?
Here is an article that explains how to resolve this problem... basically to fix this you set LocalAccountTokenFilterPolicy to True in the registry.
http://www.shirmanov.com/2011/04/winrm-access-is-denied-on-local.html