Forum / Remote Desktop Manager - Macro/Script/Tools

Connecting to Office 365 Powershell

  • Create an Issue
  • Cancel

Hello

I would like to connect to various Office 365 powershells directly from RemoteDesktopManager. My problem is the credential delivery. Normally I get the credentials with:

$LiveCred = GetCredential

Then a credential window pops up and I have to enter the crendetials of the Office 365 account I wish to connect with.

But I want to enter the credentials in the connection setting in RDM and call them together with the script. I have searched for other possibilities and found a way to setup the PSCredential manually from command line options, wich I can feed with RDM:


$User = $args[0]
$Pass = ConvertTo-SecureString -String "$args[1]" -AsPlainText -Force
$LiveCred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $Pass


But I get allways an error connecting to the Office 365 remote powershell (no access). Any ideas?


The complete script I call from RDM looks like this:

---$User = $args[0]

$Pass = ConvertTo-SecureString -String "$args[1]" -AsPlainText -Force
$LiveCred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $Pass
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Import-Module MSOnline
Connect-MsolService -Credential $LiveCred

---


Oliver
edited by OTimme on 6/12/2013

Clock7 yrs

Added the following to the script... need to convert the PSCredential to a Credential

$LiveCred = Get-Credential -Credential $PSCred

I think it works, got passed the authentication but then failed (see error below)

$User = $args[0]
$Pass = ConvertTo-SecureString -String $args[1] -AsPlainText -Force
$PSCred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $Pass
$LiveCred = Get-Credential -Credential $PSCred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Import-Module MSOnline
Connect-MsolService -Credential $LiveCred

edited by stefane on 6/12/2013

Stefane Lavergne

signaturesignature

Office365.jpg
Clock7 yrs

did not work here ... I still got the same error. It seems the submisson of the credentials to O365 fails.

Clipboard01.jpg
Clock7 yrs

I found the Problem, the special characters I normaly use in passwords! The used password is like C!ty$t0re and it seems that the special characters needs to be escaped or otherwise marked ...

Clock7 yrs

Hi there,

I got it working, but is there something I can add to the script to make is stay in the session, and thereby let me enter commands?

In my environment it connects, and then I get the PowerShell prompt...that is, I am not in the session anymore.

Thank you!

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

Not sure I understand what you mean.

What session type did you create? PowerShell? Session or Macro/Script/Tools type?

What happens? PowerShell comes up, logs you then closes?

Post a screen if possible.

Regards,

Stefane Lavergne

signaturesignature

Clock7 yrs

It is a PowerShell session where I pass on credentials as arguments, just like you wrote earlier in this thread.

This is how it is set up

image

...and when I run it, it logs on to Office 365, and ends with the following prompt:

image

Running a command from there just results in an error, since I am no longer in the session:

image

Thank you

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

Can you try a quick test? Add that exact command within the .ps1 script file. Does it work?

In other words, is it a scope issue?
edited by stefane on 6/25/2013

Stefane Lavergne

signaturesignature

Clock7 yrs

It works when included in the script

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

...but I cannot execute any commands at all related to the session I log in to in the script.

It looks like the session stops with the execution of the script.

Is there some command that will let the session stay open and wait for more commands inside the script?

This is how my script looks now:

Set-ExecutionPolicy RemoteSigned
$User = $args[0]
$Pass = ConvertTo-SecureString -String $args[1] -AsPlainText -Force
$PSCred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $Pass
$LiveCred = Get-Credential -Credential $PSCred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Import-Module MSOnline
Connect-MsolService -Credential $LiveCred

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

Ok, so it is a scoping issue. I will have a look at the code and try to figure how to resolve this issue.

Stefane Lavergne

signaturesignature

Clock7 yrs

try configuring your PowerShell session like the following:

Office365+2


Note: make sure you leave the "Run as admin" & "Run 64-bit" checked
edited by stefane on 6/25/2013

Stefane Lavergne

signaturesignature

Office365-2.jpg
Clock7 yrs

Hi Stefane,

Thank you for your response.
I have tried your suggested setup, except for the 64-bit, and it makes no change. I have also tried to run it from a colleagues machine, and his machine has the same issue.
The reason I cannot run the 32-bit is that I have the 64-bit Microsoft Online Services Module for Windows PowerShell installed. If need to run 32-bit I will have to uninstall the 64-bit and install the 32-bit, since they cannot be installed in co-existance.

Can you replicate the issue on your setup?

Thank you.

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

It Works, do not ask what has changed, but I was just playing around with the desktop shortcut functionality in RDM and tried it once more for that connection, and it worked!

Thank you for your assistance and a fantastic product!

Best Regards,
Ulrich Jorgensen
Logiqit.com ApS

Clock7 yrs

Good to here. I agree with the 64-bit, you need it checked.

As for why it runs now. In the first screen shot you are running within a PowerShell shell the command "../PowerShell.exe C:\...\..ps1" which has the effect of starting a second session from which to run the script. Once the script has terminated the session is terminated returning control to first session. The first session has no clue about the second (now closed) session therefore calling objects created by the script fails.

As for running on my machine? The answer is no, not yet. I installed the required installs (all 64-bit) but I'm still getting errors, maybe I need to reboot it did ask me but I had no time :-). The important think here is that it works for you.

Regards,

Stefane Lavergne

signaturesignature

Clock7 yrs

Hello guy's. Using this script now to connect to our Office365 environment.
I'm getting errors when using the $PASSWORD$ parameter. When I parse it in the script I see that the output is only a $ and not the whole password.
When I enter the password in the $DOMAIN$ parameter field and use this one as the password parameter it connects successfully. Anyone has an idea why it only parse a $ to the script when I use the $PASSWORD$ parameter? Fyi the password is really simple and only text.
Running v11.0.12.0

Domain+variable+is+parsed+as+the+right+password
Password+variable+is+parsed+as+%24

Domain variable is parsed as the right password.PNG
Password variable is parsed as $.PNG
Clock4 yrs

Hello Joris van der Sligte,


Have you checked the Allow password in variable option in the Securiy section of your session?
2015+12+21+14+00+04


Best regards,



Jeff Dagenais

signaturesignature

2015-12-21_14-00-04.jpg
Clock4 yrs

Jean-François Dagenais wrote:

...

Hello Jean, this solved it. Thanks for unrevealing this option smile

Clock4 yrs

Joris

I've followed this thread, but can't make it work
- are you willing to share the PS1 file?
- how/where must this file be located to be used with different office365 accounts
- username and password for the session, are the off365 credentials correct?

kind regards ReD

Clock4 yrs

Hello Red, see attached. Just translate the screnshots from dutch into your language.

LoginOffice365.ps1
screens.pdf
Clock4 yrs

Joris,

tnx, heb ik gedaan maar wil maar niet lukken
- het begint met een error
New-Object : Cannot find type [â?TypeName System.Management.Automation.PSCredential â?ArgumentList]: verify that the assembly containing this type is loaded.
At C:\Users\john\SkyDrive\Docs\Phylax\powershell\LoginOffice365.ps1:4 char:11
+ $PSCred = New-Object â?"TypeName System.Management.Automation.PSCredential â?"Ar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (smile [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

- daarna komt er een inlog scherm voor office 365, na het invoeren van de credentials krijg ik onderstaande
New-Object : Cannot find type [â?TypeName System.Management.Automation.PSCredential â?ArgumentList]: verify that the assembly containing this type is loaded.
At C:\Users\john\SkyDrive\Docs\Phylax\powershell\LoginOffice365.ps1:4 char:11
+ $PSCred = New-Object â?"TypeName System.Management.Automation.PSCredential â?"Ar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (smile [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

zal 1st eens proberen om het script los in powershell uit te voeren

Clock4 yrs

John wrote:

Joris,

tnx, heb ik gedaan maar wil maar niet lukken
- het begint met een error
New-Object : Cannot find type [â?TypeName System.Management.Automation.PSCredential â?ArgumentList]: verify that the assembly containing this type is loaded.
At C:\Users\john\SkyDrive\Docs\Phylax\powershell\LoginOffice365.ps1:4 char:11
+ $PSCred = New-Object â?"TypeName System.Management.Automation.PSCredential â?"Ar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (smile [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

- daarna komt er een inlog scherm voor office 365, na het invoeren van de credentials krijg ik onderstaande
New-Object : Cannot find type [â?TypeName System.Management.Automation.PSCredential â?ArgumentList]: verify that the assembly containing this type is loaded.
At C:\Users\john\SkyDrive\Docs\Phylax\powershell\LoginOffice365.ps1:4 char:11
+ $PSCred = New-Object â?"TypeName System.Management.Automation.PSCredential â?"Ar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (smile [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

zal 1st eens proberen om het script los in powershell uit te voeren


Any luck yet? The screens as how I put them online are from running on a RDS not a local client.
You also need to have the O365 powershell module en MSOL module installed for powershell.

Clock4 yrs

I know it's an old subject, but maybe someone can use this. We are using the next (embeded) script to connect to the most used MSOL services:

--------------------------------------------


#Created by Reinout.Dorreboom@bevio.nl

$User = $args[0]
$tenantName = $args[2]
$Password = ConvertTo-SecureString -String $args[1] -AsPlainText -Force
$creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PassWord
$Site = "https://$tenantName-admin.sharepoint.com"

#clean up opened sessions
Write-Host 'Clean up the current sessions on the computer...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Get-PSSession | Remove-PSSession
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

$Modules = @("MSOnline","SharePointPnPPowerShellOnline","SkypeOnlineConnector")

$Modules | foreach{
if (Get-Module -ListAvailable -Name MSOnline) {
Write-Host "$_ Module exists" -ForegroundColor green
} else {
Write-Host "$_ Module does not exist" -ForegroundColor red
$answer = Read-Host -Prompt "Do you want to continue? Yes (y) / No (n)"
If($answer -eq "n"){exit}
}
}

#Connect to the MS Online Services
Write-Host 'Connecting to MS Online Services...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Connect-MsolService –Credential $Creds |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Connect to SharePoint Online
Write-Host 'Connecting to SharePoint Online...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Connect-PnPOnline -Url $site -Credentials $Creds |out-null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to Exchange Online Remote Powershell and import the MS Exchange Module
Write-Host 'Connecting to Exchange Online...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ExOnSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ExOnSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to the Compliance Center Remote Powershell and import the Compliance center Module
Write-Host 'Connecting to the Compliance Center...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ComplianceSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ComplianceSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green


#Connect to Lync Online
Write-Host 'Connecting to Lync Online...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$LyncSession = New-CsOnlineSession -Credential $Creds
Import-PSSession $LyncSession -AllowClobber -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

Write-Host "`nYou are now connected to Office 365, Exchange Online, the Compliance center, Skype for Business Online and SharePoint Online" -BackgroundColor Black -ForegroundColor Yellow

-------------------------------------------

In the credential manager we use the next values:
Username: admin@domain.com
Password: AdminPassword
Domain: Tenant name (this will be used by the script to get the SharePoint url (http://[tenantname]-admin.sharepoint.com)

Then use as arguments: $USERNAME$ $PASSWORD$ $DOMAIN$

BTW do not forget to set the option in your session: Allow password in Variable (in your session -> Security Allow Password in Variable)

Hope this helps someone!

Clock3 yrs

Useful script, thanks Reinout.

A quick question to you and other script users but I see a bunch of threads where people are doing a similar thing i.e. passing variables in as arguments and then referencing them as $args[]. Is the script external or just a normal embedded script in RDM? If the later then what is the advantage of this over just referencing the variable directly in the script? For example in my script I use


$User = '$USERNAME$'


rather than

$User = $args[0]

and don't pass anything in in the arguments field.

Thanks

Alan

Clock3 yrs

Hi Alan,

Good question! I use it as embedded script, so my colleagues can use it also without needing to have the ps1 file on their computer. I do not think it will work if you use the variable straight into the script ($username$). I think Powershell will extract the variable and put the last $ behind it. (If you username is admin, then Powershell will make Admin$ from the variable $USERNAME$).

*But* I never tried it either smile

Clock3 yrs

Hi Reinout

Thanks for the response! I can confirm that including the variable directly in the embedded script does work for me though I have to surround it with single quotes to avoid issues with special characters in passwords (and possibly the issue you suggest as well).

So I use


$User = '$USERNAME$'
$PWord = ConvertTo-SecureString -String '$PASSWORD$' -AsPlainText -Force


Cheers

Alan

Clock3 yrs

Thanks Alan, that makes it all even easier!


░░░░░░░░░░░████░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░███░██░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░██░░░█░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░██░░░██░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░██░░░███░░░░░░░░░░░░░░░░░
░░░░░░░░░░░██░░░░██░░░░░░░░░░░░░░░░
░░░░░░░░░░░██░░░░░███░░░░░░░░░░░░░░
░░░░░░░░░░░░██░░░░░░██░░░░░░░░░░░░░
░░░░░░░███████░░░░░░░██░░░░░░░░░░░░
░░░░█████░░░░░░░░░░░░░░███░██░░░░░░
░░░██░░░░░████░░░░░░░░░░██████░░░░░
░░░██░░████░░███░░░░░░░░░░░░░██░░░░
░░░██░░░░░░░░███░░░░░░░░░░░░░██░░░░
░░░░██████████░███░░░░░░░░░░░██░░░░
░░░░██░░░░░░░░████░░░░░░░░░░░██░░░░
░░░░███████████░░██░░░░░░░░░░██░░░░
░░░░░░██░░░░░░░████░░░░░██████░░░░░
░░░░░░██████████░██░░░░███░██░░░░░░
░░░░░░░░░██░░░░░████░███░░░░░░░░░░░
░░░░░░░░░█████████████░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

Clock3 yrs

lol no problem (and nice graphic smile)

Clock3 yrs

Thanks for the script.
Had to fiddle around but for anyone else looking to get this to work this is what I did.

Using this script for now, removed the Sharepoint requirements in my case because we don't use it.


#Created by Reinout.Dorreboom@bevio.nl, edited by Jeffrey Veenhuis

$User = '$USERNAME$'
$PWord = '$PASSWORD$'
$Password = ConvertTo-SecureString -String $PWord -AsPlainText -Force
$creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PassWord

#Clean up opened sessions
Write-Host 'Clean up the current sessions on the computer...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Get-PSSession | Remove-PSSession
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

$Modules = @("MSOnline","SkypeOnlineConnector")

$Modules | foreach{
if (Get-Module -ListAvailable -Name MSOnline) {
Write-Host "$_ Module exists" -ForegroundColor green
} else {
Write-Host "$_ Module does not exist" -ForegroundColor red
$answer = Read-Host -Prompt "Do you want to continue? Yes (y) / No (n)"
If($answer -eq "n"){exit}
}
}

#Connect to the MS Online Services
Write-Host 'Connecting to MS Online Services...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Connect-MsolService –Credential $Creds |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to Exchange Online Remote Powershell and import the MS Exchange Module
Write-Host 'Connecting to Exchange Online...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ExOnSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ExOnSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to the Compliance Center Remote Powershell and import the Compliance center Module
Write-Host 'Connecting to the Compliance Center...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ComplianceSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ComplianceSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

Write-Host "`nYou are now connected to Office 365, Exchange Online, the Compliance center and Skype for Business Online" -BackgroundColor Black -ForegroundColor Yellow


Use the following options:


imageimage

Written a miniguide for my colleagues


1. Install msoidcli_64.msi (https://www.microsoft.com/en-us/download/details.aspx?id=28177)
2. Run Powershell as Admin and run: Set-ExecutionPolicy Unrestricted
3. Run Powershell as Admin and run: (Y to everything): Install-Module MSOnline


Everything combined should make it work for people smile

Clock2 yrs