Script to log into Office 365 with pre-entered creds

This topic contains 5 replies, has 3 voices, and was last updated by  Stuart Riesen 1 month, 2 weeks ago.

  • Author
    Posts
  • #73219

    Stuart Riesen
    Participant

    Hi I'm new to PowerShell.org

    I know how to connect to O365 through PS:

    Set-ExecutionPolicy RemoteSigned (ONLY ONCE)
    $credential = Get-Credential
    Import-Module MsOnline
    Connect-MsolService -Credential $credential
    Get-MsolUser (use this to confirm your session)

    Unfortunately it pops up asking for the username and password. What I'd like to be able to do is save the username and password so I'm not prompted for it.

    Is this possible?

  • #73223

    David Schmidtberger
    Participant

    there are several methods to achieve this, however, this is rather difficult to do securely.
    you can include credentials in scripts in plaintext (BAD IDEA!!)
    with a bit more work you can encrypt the passwords, there are various examples online for how to do this

    if you are just trying to connect random powershell sessions, you could include the connection strings in your powershell profile, and then generally only be prompted for the credentials when starting a session, or executing a command when the service has disconnected.

    i guess the answer i would give will depend on exactly how you are intending to utilize the session

    • #73255

      Stuart Riesen
      Participant

      Hi David, thanks for the quick response. The primary reason I'm looking to do it is because as a service provider I am often having to do password reset's for people and I have to log onto the portal for each account and then reset it...it takes time and is tedious. I was thinking there has to be a faster way to do it by saving the creds in the script. Does that help?

  • #73280

    Anders
    Participant

    I would do something like this

    Read-Host -AsSecureString -Prompt "Enter the password" |
    ConvertFrom-SecureString |
    Out-File C:\Temp\creds.txt

    $Pass = Get-Content C:\Temp\creds.txt | ConvertTo-SecureString
    $Cred = New-Object System.Management.Automation.PSCredential ("Username", $Pass)

  • #73289

    David Schmidtberger
    Participant

    this is similar to what i do when required.

    be aware this method will only work on one machine, you can-not copy the password file to any other machine and decrypt the password

    • #73873

      Stuart Riesen
      Participant

      Awesome! Thanks so much for your help. I've been working on this behind the scenes and just got around to actually testing it now and it works great. Once again thank you.

You must be logged in to reply to this topic.