Wednesday, August 9, 2017

New-O365PSSession.ps1

Today's script can be used with previous Set-O365EncryptedCredentials or standalone.

Scope of script is following:

  • Checks for stale O365 Sessions and closes them
  • Will use saved credentials (Set-O365EncryptedCredentials.PS1) or prompt for user to provide
  • Will fail if MSOnline Module not installed
  • Will Skip SharePoint / Skype if required modules not installed
Due to length of script unless requested will not be doing code break down.


  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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<#
.SYNOPSIS
    Connect to O365
.DESCRIPTION
    Connect to O365
        If Encrypeted path available will use that otherwise prompts for credentials.
.PARAMETER SkipSharePoint
    If no DNS for SharePoint, add this to skip SharePoint options
.PARAMETER SkipSkype
    If no DNS for Lync, add this to skip Lync options
.PARAMETER SkipExchange
    If no DNS for Exchange, add this to skip Exchange options
.PARAMETER SkipSecurity
    If no DNS for Security & Compliance Center, add this to skip Security & Compliance Center options
.PARAMETER Path
    Enter alternate path for ecrypted credential files, defualt is users local app data
.EXAMPLE
    Opens PowerShell Session for all Office365 products
    
    New-O365PSSession.ps1
.EXAMPLE
    Opens PowerShell Session for all Office365 products except Exchange online
    
    New-O365PSSession.ps1 -skipExchange
.NOTES
    Created by Chris Lee
    Date April 20, 2017

    Some code pulled from:
        PoShConnectToOffice365.ps1
        Created by DJacobs for HBS.NET
.LINK
    GitHub: https://github.com/clee1107/Public/blob/master/O365/New-O365PSSession.ps1
    Blogger:http://www.myitresourcebook.com/2017/08/new-o365pssessionps1.html
#>

[Cmdletbinding()]
Param
(
    [switch]
    $SkipSharePoint,
    [switch]
    $SkipSkype,
    [switch]
    $SkipExchange,
    [switch]
    $SkipSecurity,
    [String]
    $Path = [Environment]::GetFolderPath("LocalApplicationData")
)

#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################

## region Functions
    Function Test-Verbose
        {
            [cmdletbinding()]
            Param()
            Write-Verbose "Verbose output"
            "Regular output"
        }
    Test-Verbose
## endregion

## Check for Credential Files present
    ##Check for User file
        Write-Verbose -Message "Checking for optional user file"
        IF (!(Test-Path -Path "$Path\O365user.txt"))
            {
                $AdminName = Read-Host -Prompt "Enter your tenant UPN"       
            }
        else
            {
                Write-Host -ForegroundColor Green "User File found"
                $AdminName = Get-Content "$Path\O365user.txt"
            }
    ##Load Encrypted password file
        Write-Verbose -Message "Checking for required password file"
        IF (!(Test-Path -Path "$Path\O365cred.txt"))
            {
                $Pass = Read-Host -Prompt "Enter your tenant password" -AsSecureString `
                    | ConvertFrom-SecureString
            }
        else
            {
                Write-Host -ForegroundColor Green "Password File Found"
                $Pass = Get-Content "$Path\O365cred.txt" | ConvertTo-SecureString
            }
## Create Cred variable
    Write-Verbose -Message "Creating Credential varialble from files"
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass

## Check for O365 Component Modules
    ## MSOnline (AzureAD)
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "MSOnline Module not found."
                Throw  "MSOnline Module not found. Must install to continue.  Can be installed via PowerShell script: Install-O365Modules.PS1"
            }
    ## SharePoint Online
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing SharePoint Module"
                Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "SharePoint Online Module not found."
                Write-Error  "SharePoint Online Module not found, will be skiped.  Can be installed via PowerShell script: Install-O365Modules.PS1"
                $SkipSharePoint = $True
            }
    ## Skype for Business
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Skype for Business Module"
                Import-Module SkypeOnlineConnector -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "Skype for Business Module not found."
                Write-Error  "Skype for Business Module not found, will be skiped.  Can be installed via PowerShell script: Install-O365Modules.PS1"
                $SkipSkype = $True
            }


## Connect of O365 with error checks
    ##Connect MSOnline (Azure Active Directory)
        Write-Verbose -Message "Connecting MSOnline (Office 365)"
        ## Office 365
            Try #Check if already connected to MSOnline
                {
                    Write-Verbose -Message "Checking if already connected to MSOnline (Azure Active Directory)"
                    Get-MsolDomain -ErrorAction Stop > $null
                    Write-Host -ForegroundColor Green "Already Connected to MSOnline (Azure Active Directory)"
                }
            Catch #Connect to MSOline
                {
                    Try #Try to connect to MSOnline
                        {
                            Write-Verbose -Message "Connecting MsolService"
                            Connect-MsolService -Credential $cred -ErrorAction Stop
                            Get-MsolDomain -ErrorAction Stop > $null
                            Write-Host -ForegroundColor Green "Connected to MSOnline (Azure Active Directory)"
                        }
                    Catch [Microsoft.Online.Administration.Automation.MicrosoftOnlineException] #Failed to connect bad credentials
                        {
                            Write-Error -Message "Error. Failed to Connect to MsolService because bad username or password." -ErrorAction Stop
                        }
                    Catch #Failed to connect other then credential issue
                        {
                            #$_ | fl * -Force
                            Write-Error -Message "Error. Failed to connect to MsolService because $_" -ErrorAction Stop
                        }
                    if ($ShowProgress) #Present MSOL Domains connected to
                        {
                            Write-Verbose -Message "$(Get-Date -f o) Listing MSOL Domains"
                            Get-MsolDomain | ft -AutoSize
                        }
                }

            
    ##Connect SharePoint Online
        Write-Verbose -Message "Connecting SharePoint Online"
        ##SharePoint
            if (-not $SkipSharePoint)
                {
                    Try #Check if already connected to Sharepoint Online
                        {
                            Write-Verbose -Message "Checking if already connected to SharePoint Online"
                            Get-SPOsite -ErrorAction Stop > $null
                            Write-Host -ForegroundColor Green "Already Connected to SharePoint Online"
                        }
                    Catch #Connect to SharePoint Online
                        {
                            Write-Verbose -Message "Not connected to SharePoint Online"
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Connecting SP Online Service"
                                    Connect-SPOService -Url https://$spAdminName-admin.sharepoint.com -Credential $cred -ErrorAction Stop
                                    Get-SPOSite -ErrorAction Stop > $null
                                    Write-Host -ForegroundColor Green "Connected to SharePoint Online"
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot connect to 'SPOService' because $_" -ErrorAction Stop
                                }
                            if ($ShowProgress) 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Listing SP Online Sites"
                                    Get-SPOSite | ft -AutoSize
                                } 
                        }
                    
                } 
            else   
                {
                    Write-Verbose -Message "Skipping SharePoint"
                }
    ##Connect Skype for Business
        Write-Verbose -Message "Connecting Skype for Business"
        if (-not $SkipSkype) 
            {   
                Try 
                    {
                        Write-Verbose -Message "Checking if already connected to Skype for Business"
                        If ((Get-PSSession | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -like "Opened"}))
                            {
                                Write-Host -ForegroundColor Green "Already Connected to Skype for Business"
                                Write-Verbose -Message "Removing broken PSSessions for Skype for Business"
                                $PSSessionIDs = Get-PSSession `
                                    | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -notlike "Opened"} `
                                    | Select-Object Id
                                If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                    {
                                        Write-Verbose -Message "No broken sessions to remove"
                                    }
                                else 
                                    {
                                        Foreach ($PSessionID in $PSSessionIDs)
                                            {Remove-PSSession $PSessionID}
                                        Write-Verbose -Message "All broken Skype for Business sessions removed"
                                    }
                            }
                    }
                Catch 
                    {
                        Try 
                            {
                                Write-Verbose -Message "$(Get-Date -f o) Creating Skype for Business Session"
                                $skypeSession = New-CsOnlineSession -Credential $cred -ErrorAction Stop
                            }
                        Catch 
                            {
                                Write-Warning "$(Get-Date -f o) Error. Cannot connect to Skype for Business because $_"
                            }
                        Try 
                            {
                                Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Skype for Business"
                                $null = Import-PSSession $skypeSession -AllowClobber -ErrorAction Stop
                                Write-Verbose -Message "Successfully imported PSSession for Skype for Business."
                            }
                        Catch 
                            {
                                Write-Error -Message "Failed to import PSSession for Skype for Business." -ErrorAction Continue
                            }
                    }
                if ($ShowProgress) 
                    {
                        if (Get-Command -Name Get-CsMeetingConfiguration -ErrorAction SilentlyContinue) 
                            {
                                Write-Verbose -Message "Successfully connected to Skype for Business."
                            } 
                        else 
                            {
                                Write-Warning -Message "Error. Did not connect to Skype for Business."
                            }
                    }
                If ((Get-PSSession | Where-Object {$_.ComputerName -like "admin1a*" -AND $_.State -like "Opened"}))
                    {
                        Write-Host -ForegroundColor Green "Connected to Skype for Business"
                    }
                else 
                    {
                        Write-Host -ForegroundColor Red "Failed to connect to Skype for Business"
                    }
            } 
        else 
            {
                Write-Verbose -Message "Skipping Skype for Business"
            }
     
    ##Connect Exchange Online
        Write-Verbose -Message "Connecting Exchange Online"
        #$Exchange
            if (-not $SkipExchange) 
                {
                    Write-Verbose -Message "Checking if already connected to Exchange Online"
                    If ((Get-PSSession | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -like "Opened"}))
                        {
                            Write-Host -ForegroundColor Green "Already Connected to Exchange Online"
                            Write-Verbose -Message "Removing broken PSSessions for Exchange"
                            $PSSessionIDs = Get-PSSession `
                                | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -notlike "Opened"} `
                                | Select-Object Id
                            If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                {
                                    Write-Verbose -Message "No broken sessions to remove"
                                }
                            else 
                                {
                                    Foreach ($PSessionID in $PSSessionIDs)
                                        {Remove-PSSession $PSessionID}
                                    Write-Verbose -Message "All broken Exchange sessions removed"
                                }
                        }
                    else 
                        {
                            Try
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Creating Exchange Session"
                                    $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange `
                                        -ConnectionUri "https://outlook.office365.com/powershell-liveid/" `
                                        -Credential $cred `
                                        -Authentication "Basic" `
                                        -AllowRedirection `
                                        -ErrorAction Stop
                                    Write-Verbose -Message "Successfully created Exchange Session."      
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot talk to Exchange because $_" -ErrorAction Stop
                                }
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Exchange"
                                    $null = Import-PSSession $exchangeSession -AllowClobber -ErrorAction Stop -DisableNameChecking
                                    Write-Verbose -Message "Imported PSSession for Exchange."
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot Import PSSession for Exchange because $_" -ErrorAction Stop
                                }
                            if ($ShowProgress) 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Listing Accepted Domains"
                                    Get-AcceptedDomain | Format-Table -Property DomainName, DomainType, IsValid -AutoSize
                                }
                            If ((Get-PSSession | Where-Object {$_.ComputerName -like "outlook*" -AND $_.State -like "Opened"}))
                                {
                                    Write-Host -ForegroundColor Green "Connected to Exchange"
                                }
                            else 
                                {
                                    Write-Host -ForegroundColor Red "Failed to connect to Exchange"
                                }
                        }
                }
            else 
                {
                    Write-Verbose -Message "Skipping Exchange"
                }
    ##Connect Security & Compliance Center
        Write-Verbose -Message "Connecting Security & Compliance Center"
        #$Exchange
            if (-not $SkipSecurity) 
                {
                    If ((Get-PSSession | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -like "Opened"}))
                        {
                            Write-Host -ForegroundColor Green "Already Connected to Security & Compliance Center Online"
                            Write-Verbose -Message "Removing broken PSSessions for Security & Compliance Center"
                            $PSSessionIDs = Get-PSSession `
                                | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -notlike "Opened"} `
                                | Select-Object Id
                            If ($PSSessionIDs -eq $null -OR $PSSessionIDs -eq "")
                                {
                                    Write-Verbose -Message "No broken sessions to remove"
                                }
                            else 
                                {
                                    Foreach ($PSessionID in $PSSessionIDs)
                                        {Remove-PSSession $PSessionID}
                                    Write-Verbose -Message "All broken Exchange sessions removed"
                                }
                        }
                    else 
                        {
                             Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Creating Security & Compliance Center Session"
                                    $securitySession = New-PSSession -ConfigurationName Microsoft.Exchange `
                                        -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid/" `
                                        -Credential $cred `
                                        -Authentication "Basic" `
                                        -AllowRedirection `
                                        -ErrorAction Stop
                                        Write-Verbose -Message "Successfully created Exchange Security & Compliance Session."      
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot talk to Exchange Security & Compliance because $_" -ErrorAction Stop
                                }
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing PSSession for Security & Compliance Center"
                                    $securitySession = Import-PSSession $securitySession -Prefix cc -AllowClobber -ErrorAction Stop -DisableNameChecking
                                }
                            Catch 
                                {
                                    Write-Warning "Error. Cannot Import PSSession for Security & Compliance Center because $_"
                                }                    
                            if ($ShowProgress) 
                                {
                                    if (Get-Command -Name Get-CsMeetingConfiguration -ErrorAction SilentlyContinue) 
                                        {
                                            Write-Verbose -Message "Successfully connected to Security & Compliance Center."
                                        } 
                                    else 
                                        {
                                            Write-Warning -Message "Error. Did not connect to Security & Compliance Center."
                                        }
                                }
                            If ((Get-PSSession | Where-Object {$_.ComputerName -like "*compliance.protection.outlook*" -AND $_.State -like "Opened"}))
                                {
                                    Write-Host -ForegroundColor Green "Connected to Security & Compliance Center"
                                }
                            else 
                                {
                                    Write-Host -ForegroundColor Red "Failed to connect to Security & Compliance Center"
                                }
                        }
                    
                } 
            else 
                {
                    Write-Verbose -Message "Skipping Security & Compliance Center"
                }


Full script can be accessed from following link:
https://github.com/clee1107/Public/blob/master/O365/New-O365PSSession.ps1
Further reference links for PowerShell cmdlets used can be found on following post:

Code Snippets created via: http://hilite.me/

No comments:

Post a Comment