Login-AzureRMAccount returns "Unknown User Type" - powershell

As the title implies, I'm trying to automate the login process to AzureRMAccount in Powershell.
I've scoured every forum on every website I can find trying every different combination of solutions (well, except for the solution that works).
Every time I try to automate the login process of my Azure account, I get an error :
Unknown User Type
Yes, I have full access to this account, and Yes it does work fine if I omit all of the parameters and allow for the interactive username/password dialog.
I have even tried to simply call the Get-Credentials and push those into a variable and then call Login-AzureRMAccount using those creds....no luck.
Add-AzureRMAccount fails too.
Any help would be appreciated.

I did find one solution, although it's not the most secure solution as it generates a disk file putting your information at risk if someone were to gain access to the machine on which the Powershell code is executing.
You can login interactively and immediately export the context to a json file, Then at a later time, import that json file as the current context to bypass login
PS C:\> Save-AzureRmContext -Profile (Add-AzureRmAccount) -Path C:\test.json
then in a later session, Import the context
PS C:\> Import-AzureRmContext -Path C:\test.json
Again, this is not the most secure option but it did achieve the results. I would love to have a more secure option.

Related

Remote execution of powershell script with autosys - to interact with IE _ComObject

I have a Powershell script designed to automate the testing of some URLs. The script invokes an Internet Explorer session as such:
$IEProcess = Start-Process -FilePAth 'C:\Program Files (x86)\Internet Explorer\iexplore.exe' -ArgumentList "-private $url"
$Shell = New-Object -ComObject Shell.Application
$IE = $Shell.Windows()
It then proceeds to use the $IE object to navigate to different URLs, perform various checks against the pages HTML document bodies and take screenshots of the resulting web pages. Ultimately, the IE session is ended and the screenshots are distributed via email as attatchments.
The script works perfectly when logged onto the virtual host-machine with a service account, that has the necessary permissions for single-sign-on to the various URLs. However, the requirement is for the script to run remotely as a scheduled task, on a daily basis. There should be no interaction by a user other than opening the resulting email.
I have had a job set up in AutoSys to execute the script remotely, once a day, with highest privileges; but the script fails to complete as expected. Specifically, the .Windows() method fails passing the following error message:
Exception calling "Windows" with "0" argument(s): "The server process could not
be started because the configured identity is incorrect. Check the username an
d password. (Exception from HRESULT: 0x8000401A)"
I have to give the job of scheduling the task in autosys to someone else (for security reasons) but I trust that they have configured the job with the appropriate username/password for the necessary service account.
Some online sources suggest to me that the issue might lie with trying to use _ComObjects remotely, and that instances of Internet Explorer require an interactive user session with a UI - which isn't standard config for an autosys batch job.
I have had my autosys-guy add a flag to the job description which should make the user session "interactive", but the script still doesn't execute correctly.
I'm looking for some general insight on the topic and hopefully a solution to get the job running. If anyone cares to help me out I would greatly appreciate it! :)
I also have a more focussed question:
Even if I managed to get a handle on the IE session, should I expect the screenshots that the script takes to fail since the screen buffer for the VM has no monitor to render to? - The images are bitmap and refer to the IE shell objects "position", "width" and "height" for capture placement/dimensions; which presumably mean nothing without a screen resolution??
Thank you for taking the time to read my issue!

Is there a way to change the service account from "This account" to "Log in as" using Powershell?

New to powershell but bear with me. I am trying to automate an install of Prosystem Fx Engagement, but need to install a SQL instance. I have already done this part, but I will also need to automate the changing of a services account within services.msc. It will need to be changed from "This account" to "Log in as Local System Account"
https://imgur.com/en9COWl
The name of the service is MSSQL$PROFXENGAGEMENT, and the display name of the service is SQL Server (PROFXENGAGEMENT).
I don't really want to use the method below because the password is visible on the .ps file. I tried looking around but was not able to find anything. Is this even possible?
$LocalSrv = Get-WmiObject Win32_service -filter "name='MSSQL$PROFXENGAGEMENT'"
$LocalSrv.Change($null,$null,$null,$null,$null,$false,"DOMAIN\administrator","PASSWORD")
As for the method you are saying you don't want to use for the account change activity. You don't have to and should not put plain text password in scripts.
You can prompt for the password, store that in a variable and use it. Yet, that means a human has to be there to address that, so, not very automated.
So, this means you need to set the credentials in a file or other store and call that from your script.
Meaning like what is described below. This of course has to be done in advance of any other use case that will need it.
using secure password with multiple users without prompt
#saving credentials
Get-Credential | Export-CliXml -Path c:\credential.xml
#importing credentials to a variable
$Credential = Import-CliXml -Path c:\credential.xml
A YouTube Video on the topic:
Learn to securely use Passwords with PowerShell
You could also use the Windows Credential Store, and call it from there. Also shown in the above video.
Using Windows Credential Manager
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde
https://www.powershellgallery.com/packages/CredentialManager/1.0
https://www.experts-exchange.com/questions/29061982/Powershell-Using-credentials-stored-in-Credential-Manager.html

What should I use in place of Select-AzureSubscription?

I am trying to remove deprecated cmdlets in a powershell script and one of the cmdlets is Select-AzureSubscription. I tried replacing it with Select-AzureRmSubscription but that requires user interaction to authenticate. Does anyone know what Azure-Rm cmdlet I should be using instead?
Select-AzureRmSubscription does change the approach that Azure uses for authentication. I had the same pain points when I converted my scripts.
The official way of approaching this via scripting is as follows -
$profile = Login-AzureRmAccount
Save-AzureRMProfile -Profile $profile -path $path
You can then use Select-AzureRmSubscription to none-interactively load those saved profiles.
Although ultimately I didn't go this route, I decided to add another layer of security and use a machine based certificate to encrypt / decrypt credentials to pass to Login-AzureRmAccount This way I could manage multiple sets of accounts and never have to be concerned about those tokens being exposed on vulnerable machines.

Add-AzureAccount : Index was out of range. Must be a non-negative and less than the size of the collection

On 4th of August a new version of the Azure powershell module (0.8.7.1) was released. In it is the ability to create credentials which you could then pass to the Add-AzureAccount function. Add-AzureAccount allows you to pull in an account to work with in the current PowerShell session.
$userName = "buildmaster#someaccount.onmicrosoft.com"
$securePassword = ConvertTo-SecureString -String "somepassword." -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureAccount -Credential $cred
This allowed me to get away from a popup window or messing with a settings file.
It seems to have stopped working! Both Add-AzureAccount (which pops up a window) and the credential based way. They now return an index was out of range issue.
Add-AzureAccount : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
At S:\QA\Azure Scripts\cm-azure-helpers.psm1:1128 char:5
+ Add-AzureAccount
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureAccount], ArgumentOutOfRangeException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
Digging deeper with Fiddler shows that the OAuth call to the back end service seems to work. I get a token returned. But then I also get a 302 in the middle of the process stating that the page has moved. I don't know if that redirect was there when it was working previously or not.
Has anyone else experienced the Add-AzureAccount function just stop working like this? And more importantly - have you found a way around it?
Update - More info
I have now tried on several boxes under different azure accounts and seem to have the same results. I get a valid auth token returned with a redirect in the middle (not sure if that is an issue or not) and then get the index was out of range.
I have done this with the following variations:
PS:3 Azure Module: 0.8.6
PS:3 Azure Module: 0.8.7
PS:4 Azure Module: 0.8.6
PS:4 Azure Module: 0.8.7
I know exactly what caused this error for me, and how I worked around it (I thought I was the only one who had seen this :))
What had happened is that I had accidentally added a bogus/empty subscription to my account. And this empty subscription had been set to my "default" subscription.
Run "get-azuresubscription -default" to see what your default subscription is. You can then "remove" any junk subscriptions using "remove-azuresubscription" command.
You can then of course set a new azure subscription for your "default" using PS.
I actually reported this to the Azure PowerShell team now to get a better error message during this scenario.
Hopefully this solved your problem, it's possible other errors manifest the same error message.
If you do a fiddler trace, you should see that right after the login call (where PowerShell passes in your username/password, there should be 1 or multiple calls to GET /subscriptions.
Check the response to see whether there is anything suspicious there. Like, any of them return an empty body, empty array, subscription with id, name, etc..
I had a similar problem recently. The "fix" was for me was to delete the files at C:\Users[username]AppData\Roaming\Windows Azure Powershell (esp. the WindowsAzureProfile.xml file). The next time I ran Add-AzureAccount, the necessary files were created and all was well.
Please use:
Add-AzureRmAccount -SubscriptionId "id";
for login

Validate Service Account Powershell

I want to write a Powershell script that will validate a large number of service accounts that was provided to me by my AD team. Not that I don't trust them but I want to cycle thru each domain username and password to see if it logs in or fails. I am looking for some suggestions so far my attempts have failed (see post http://tjo.me/fKtvPM).
Thanks
P.S. I don't have access to AD so I have to try to login using the credentials to test.
This is really hacky (ugly for least-privileged model), but if you know that all of the service accounts have access to a particular program / file, you can try to start a process using their credentials.
$cred = get-credential # however you're getting the info from AD team, pass it hear to get-credential
start-process powershell -argumentlist "-command","exit" -cred (get-credential)
$? # if $true, process started (and exited) successfully, else failed (either bad creds or account can't access powershell.exe
Unfortunately, since you can't query AD directly, I think any solution is going to be a bit of a hack, since by definition you're going to have to simulate logging in as the user account.