Connessione Office 365 da PowerShell


Tratto da http://blogs.pulsarit.net/2015/06/connessione-office-365-da-powershell/ un grazie ad Andrea!
******************************************************************************
Chi come me amministra o gestisce un tenant Office365 con PowerShell apprezzerà particolarmente questo post :-)
Una delle parti più “noiose” è la connessione ai vari servizi del tenant, io ho risolto in questo modo.
In sostanza si tratta di aggiungere due funzioni al profile PowerShell.
Il principale requisito è PowerShell 3.0 o superiore, già presente sui seguenti sistemi operativi: Windows Server 2012/2012 R2, Windows 8/8.1, e Windows 10 ovviamente :-)
Se si utilizza Windows 7 o Windows Server 2008 R2, bisogna installare il Windows Management Framework 3.0, che include la PowerShell 3.0, disponibile qui.
Innanzitutto installiamo i requisiti:
Per verificare se ci sono aggiornamenti, la lista ufficiale dei primi due è disponibile qui.
Avviamo una PowerShell amministrativa e, per prima cosa, verifichiamo che esista il “profile” con questo comando:
1
Test-Path $Profile
Se l’output è “False” non esiste, per cui lo creiamo con il comando:
1
New-Item -Path $Profile -Type File -Force
Modifichiamo l’Execution policy per richiedere la firma solo per l’esecuzione di script remoti:
1
if ((Get-ExecutionPolicy) -eq "AllSigned") {Set-ExecutionPolicy -ExecutionPolicy RemoteSigned}
Ora possiamo aggiungere la funzione al profile.
Si può usare qualunque editor di testo, ma io consiglio di usare l’ISE di PowerShell.
Sempre dalla PowerShell amministrativa eseguire
1
ise $Profile
Aggiungere queste due funzioni:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
function Connect-O365 {
  param(
  [switch]$Office365,
  [switch]$Exchange,
  [switch]$Lync,
  [switch]$SharePoint
  )
  if (!($AzureAD -or $Exchange -or $Lync -or $SharePoint)) {
    $all = $true
  }
  # Impostazione variabili
  # URL di accesso Exchange Online
  # FQDN accesso Skype for Business Online
  $LyncOnline = "webdir.online.lync.com"
  # Credenziali Tenant admin
  $O365Cred = Get-Credential -Message "Inserire le credenziali di un admin del tenant Office 365"
  # Verifica del formato utente
  if ($O365Cred.UserName -notmatch '.*\@.*') {
    Write-Warning "L'utente deve essere in formato UserPrincipalName (admin@tenant.onmicrosoft.com o admin@dominio_federato)"
    return
  }
  # Recupero dominio dal Tenant Admin
  $AdminDomain = ($O365Cred.UserName -split '@')[1]
  # Composizione FQDN Lyncdiscover
  $lyncdiscover = "lyncdiscover." + $AdminDomain
  # Lista tutti i moduli
  $Modules = Get-Module -ListAvailable -Refresh
  $Error.Clear()
  # Connessione Azure AD
  if ($Office365 -or $all) {
    if ($Modules | Where-Object {$_.Name -eq "MSOnline"}) {
      Import-Module MSOnline -ErrorAction Stop
      try {
        $Error.Clear()
        Write-Host "Connessione in corso al tenant Office 365"
        $MSOLService = Connect-MsolService -Credential $O365Cred -ErrorAction SilentlyContinue
        if ($Error.Count -eq 0) {
          $tenantDNS = (Get-MsolDomain | where IsDefault -eq "True").Name
          Write-Host -ForegroundColor Green "Connesso al tenant Office 365 $tenantDNS"
         
          ##
          $hostUIO365 = (Get-MsolDomain -Authentication Federated).name
          $tenant = (Get-MsolAccountSku)[0].AccountName
          # Composizione URL di gestione SharePoint Online
          $SPURL = "https://" + $tenant + "-admin.sharepoint.com"
        }
      }
      catch {
        Write-Host -ForegroundColor Red "Impossibile connettersi al tenant Office 365`n Error:" $Error
        Return
      }
    }
    else {
      Write-Host -ForegroundColor Red "Forse il modulo Azure Active Directory Module for Windows PowerShell non è installato`n Error:" $_
      # Return
    }
  }
  $Error.Clear()
  # Connessione Exchange Online
  if ($Exchange -or $all) {
    try {
      $Global:EOLSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $URI -Credential $O365Cred -Authentication Basic -AllowRedirection -ErrorAction SilentlyContinue
   
      if ($Error.Count -eq 0) {
        Write-Host "Importazione sessione Exchange"
        $ImportResults = Import-PSSession -Session $EOLSession
        Write-Host -ForegroundColor Green "Connesso alla sessione amministrativa Exchange`nImported" $ImportResults.ExportedFunctions.count "Functions"
        # $host.UI.RawUI.WindowTitle = "Tenant: " + $(Get-FederatedOrganizationIdentifier).AccountNamespace
        $hostUIEOP = (Get-FederatedOrganizationIdentifier).AccountNamespace
        $host.UI.RawUI.WindowTitle = "Tenant: " + $hostUIEOP + " - Domini federati: " + $hostUIO365
      }
    }
    catch {
      Write-Host -ForegroundColor Red "Impossibile connettersi alla sessione Exchange Online`n Error:" $Error
    }
  }
   
  # Connessione Skype for Business Online
  if ($Lync -or $all) {
    if ($(Resolve-DnsName -type CNAME $lyncdiscover -ErrorAction SilentlyContinue).NameHost -eq $LyncOnline) {
      if ($Modules | Where-Object {$_.Name -eq "LyncOnlineConnector"}) {
        Import-Module LyncOnlineConnector
        try {
          $Error.Clear()
          $Global:LyncSession = New-CsOnlineSession -Credential $O365Cred -ErrorAction SilentlyContinue
          if ($Error.Count -eq 0) {
            Write-Host "Importazione sessione Lync"
            $ImportResults = Import-PSSession -Session $LyncSession
            Write-Host -ForegroundColor Green "Connesso alla sessione amministrativa Lync`nImported" $ImportResults.ExportedFunctions.count "Functions"
          }
        }
        catch {
          Write-Host -ForegroundColor Red "Impossibile connettersi alla sessione Lync Online`n Error:" $Error
        }
      }
      else {
        Write-Host -ForegroundColor Red "Forse il modulo Lync Online non è installato`n Error:" $_
      }
    }
    else {
      Write-Host -ForegroundColor Red "Il record DNS Lyncdiscover non esiste o non corrisponde al tenant Office 365"
    }
  }
  # Connessione SharePoint Online
  if ($SharePoint -or $all) {
    if ($(Resolve-DnsName -type CNAME $lyncdiscover -ErrorAction SilentlyContinue).NameHost -eq $LyncOnline) {
      if ($Modules | Where-Object {$_.Name -eq "Microsoft.Online.SharePoint.PowerShell"}) {
        Import-Module Microsoft.Online.SharePoint.PowerShell
        try {
          $Error.Clear()
          Write-Host "Connessione in corso a SharePoint Online"
          Connect-SPOService -Url $SPURL -credential $O365Cred
          if ($Error.Count -eq 0) {
            Write-Host -ForegroundColor Green "Connesso alla sessione amministrativa di SharePoint Online"
          }
        }
        catch {
          Write-Host -ForegroundColor Red "Impossibile connettersi al SharePoint Online`n Error:" $Error
        }
      }
      else {
        Write-Host -ForegroundColor Red "Forse il modulo SharePoint Online non è installato`n Error:" $_
        # Return
      }
    }
    else {
      Write-Host -ForegroundColor Red "Il record DNS SharePoint non esiste o non corrisponde al tenant Office 365"
    }
  }
}
function Disconnect-O365 {
  if ($Global:EOLSession) {
    Write-Host "Rimozione sessione amministrativa Exchange Online"
    Remove-PSSession $EOLSession
  }
  if ($Global:LyncSession) {
    Write-Host "Rimozione sessione amministrativa Skype for Business Online"
    Remove-PSSession $LyncSession
  }
  if ($(Get-Module Microsoft.Online.SharePoint.PowerShell)) {
    Write-Host "Rimozione sessione amministrativa SharePoint Online"
    Disconnect-SPOService
  }
}
Adesso, ogni volta che si apre una PowerShell, è sufficiente richiamare la funzione con il comando
1
Connect-O365
e nel popup di richiesta credenziali inserire un amministratore del tenant.
Se appare una richiesta di avviare il servizio WinRM, rispondere Yes.
E’ dovuto al caricamento del modulo LyncOnline nella sessione PowerShell amministrativa.
Volendo è possibile connettersi solo ad alcuni servizi, ad esempio per Exchange Online e Lync Online
1
Connect-O365 -Exchange -Lync
Le opzioni disponibili sono:
1
2
3
4
-Office365
-Exchange
-Lync
-SharePoint
Per disconnettere le sessioni, eseguire
1
Disconnect-O365

Commenti

Post popolari in questo blog

Come e quando smantellare i server Exchange in una distribuzione ibrida

Manage Room Mailbox by using PowerShell

How to reset an Office 365 install to the initial activation/install state