Public/Get-LAConnected.ps1

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
<#
.EXTERNALHELP PSCloudConnect-help.xml
#>

function Get-LAConnected {
    
 
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param
    (

        [parameter(Position = 0, Mandatory = $true)]
        [string] $Tenant,

        [parameter(Position = 1, Mandatory = $false)]
        [string] $User,
                           
        [Parameter(Mandatory = $false)]
        [switch] $Exchange,
                              
        [Parameter(Mandatory = $false)]
        [switch] $MSOnline,
                       
        [Parameter(Mandatory = $false)]
        [switch] $All365,
                
        [Parameter(Mandatory = $false)]
        [switch] $Azure,    

        [parameter(Mandatory = $false)]
        [switch] $Skype,
          
        [parameter(Mandatory = $false)]
        [switch] $SharePoint,
         
        [parameter(Mandatory = $false)]
        [switch] $Compliance,

        [parameter(Mandatory = $false)]
        [switch] $AzureADver2,
               
        [Parameter(Mandatory = $false)]
        [switch] $MFA,

        [parameter(Mandatory = $false)]
        [switch] $Delete365Creds
        
    )

    Begin {
        if ($Tenant -match 'onmicrosoft') {
            $Tenant = $Tenant.Split(".")[0]
        }
        if (! $User) {
            $User = "Default"
        }
    }
    Process {

        $RootPath = $env:USERPROFILE + "\ps\"
        $KeyPath = $Rootpath + "creds\"

        # Delete invalid or unwanted credentials
        if ($Delete365Creds) {
            Remove-Item ($KeyPath + "$($Tenant).$($user).cred") 
            Remove-Item ($KeyPath + "$($Tenant).$($user).ucred")
        }
        # Create Directory for Transact Logs
        if (!(Test-Path ($RootPath + $Tenant + "\logs\"))) {
            New-Item -ItemType Directory -Force -Path ($RootPath + $Tenant + "\logs\")
        }
        Try {
            Start-Transcript -ErrorAction Stop -path ($RootPath + $Tenant + "\logs\" + "transcript-" + ($(get-date -Format _yyyy-MM-dd_HH-mm-ss)) + ".txt") 
        }
        Catch {
            Stop-Transcript 
            Start-Transcript -path ($RootPath + $Tenant + "\logs\" + "transcript-" + ($(get-date -Format _yyyy-MM-dd_HH-mm-ss)) + ".txt")
        }
        # Create KeyPath Directory
        if (!(Test-Path $KeyPath)) {
            try {
                New-Item -ItemType Directory -Path $KeyPath -ErrorAction STOP | Out-Null
            }
            catch {
                throw $_.Exception.Message
            }           
        }
        if ($Exchange -or $MSOnline -or $All365 -or $Skype -or $SharePoint -or $Compliance -or $AzureADver2) {
            if (Test-Path ($KeyPath + "$($Tenant).$($user).cred")) {
                $PwdSecureString = Get-Content ($KeyPath + "$($Tenant).$($user).cred") | ConvertTo-SecureString
                $UsernameString = Get-Content ($KeyPath + "$($Tenant).$($user).ucred")
                $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $UsernameString, $PwdSecureString 
            }
            else {
                $Credential = Get-Credential -Message "Enter a username and password"
                $Credential.Password | ConvertFrom-SecureString | Out-File ($KeyPath + "$($Tenant).$($user).cred") -Force
                $Credential.UserName | Out-File ($KeyPath + "$($Tenant).$($user).ucred")
            }
        }
        if ($MSOnline -or $All365) {
            # Office 365 Tenant
            Try {
                Import-Module MsOnline -ErrorAction Stop
            }
            Catch {
                Write-Output "MSOnline module is required"
                Write-Output "To download the prerequisite and MSOnline module:"
                Write-Output "https://technet.microsoft.com/en-us/library/dn975125.aspx"
            }
            Connect-MsolService -Credential $Credential
        }
        if ($Exchange -or $All365) {
            if (! $MFA) {
                # Exchange Online
                $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell -Credential $Credential -Authentication Basic -AllowRedirection 
                Import-Module (Import-PSSession $exchangeSession -AllowClobber) -Global | Out-Null
            }
            else {
                Try {
                    Connect-EXOPSSession -UserPrincipalName $Credential.UserName -ErrorAction Stop
                } 
                Catch [System.Management.Automation.CommandNotFoundException] {
                    Write-Output "Exchange Online MFA module is required"
                    Write-Output "To download the Exchange Online Remote PowerShell Module for multi-factor authentication,"
                    Write-Output "in the EAC (https://outlook.office365.com/ecp/), go to Hybrid > Setup and click the appropriate Configure button."
                }
            }
        }
        # Security and Compliance Center
        if ($Compliance -or $All365 -and (! $MFA)) {
            $ccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection
            Import-Module (Import-PSSession $ccSession -AllowClobber) -Global | Out-Null
        }
        # Skype Online
        if ($Skype -or $All365) {
            if (! $MFA) {
                Try {
                    $sfboSession = New-CsOnlineSession -ErrorAction Stop -Credential $Credential
                }
                Catch [System.Management.Automation.CommandNotFoundException] {
                    Write-Output "Skype for Business Online Module not found. Please download and install it from here:"
                    Write-Output "https://www.microsoft.com/en-us/download/details.aspx?id=39366"
                }
                Catch {
                    $_
                }
                Import-Module (Import-PSSession $sfboSession -AllowClobber) -Global | Out-Null
            }
            else {
                Try {
                    $sfboSession = New-CsOnlineSession -UserName $Credential.UserName -ErrorAction Stop
                }
                Catch [System.Management.Automation.CommandNotFoundException] {
                    Write-Output "Skype for Business Online Module not found. Please download and install it from here:"
                    Write-Output "https://www.microsoft.com/en-us/download/details.aspx?id=39366"
                }
                Catch {
                    $_
                }
            }
        }
        # SharePoint Online
        if ($SharePoint -or $All365) {
            Try {
                Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking -ErrorAction Stop
            }
            Catch {
                Write-Output "Unable to import SharePoint Module"
                Write-Output "Ensure it is installed, Download it from here: https://www.microsoft.com/en-us/download/details.aspx?id=35588"
            }
            if (! $MFA) {
                Connect-SPOService -Url ("https://" + $Tenant + "-admin.sharepoint.com") -credential $Credential
            }
            else {
                Connect-SPOService -Url ("https://" + $Tenant + "-admin.sharepoint.com")
            }
        }
        # Azure
        if ($Azure) {
            Get-LAAzureConnected
        }
        # Azure AD
        If ($AzureADver2) {
            if (! $MFA) {
                Try {
                    Install-Module -Name AzureAD -MinimumVersion '2.0.0.131' -ErrorAction Stop
                    Import-Module -Name AzureAD -MinimumVersion '2.0.0.131' -ErrorAction Stop
                    Connect-AzureAD -Credential $Credential -ErrorAction Stop
                }
                Catch {
                    Write-Output "There was an error Connecting to Azure Ad - Ensure the module is installed"
                    Write-Output "Download PowerShell 5 or PowerShellGet"
                    Write-Output "https://msdn.microsoft.com/en-us/powershell/wmf/5.1/install-configure"
                }
                
            }
            else {
                Try {
                    Install-Module -Name AzureAD -MinimumVersion '2.0.0.131' -ErrorAction Stop
                    Import-Module -Name AzureAD -MinimumVersion '2.0.0.131' -ErrorAction Stop
                    Connect-AzureAD -Credential $Credential -ErrorAction Stop
                }
                Catch {
                    Write-Output "There was an error Connecting to Azure Ad - Ensure the module is installed"
                    Write-Output "Download PowerShell 5 or PowerShellGet"
                    Write-Output "https://msdn.microsoft.com/en-us/powershell/wmf/5.1/install-configure"
                }
            }
        }
    }
    End {
    } 
}

function Get-LAAzureConnected {
    Install-Module -Name AzureRM -MinimumVersion '4.2.1'
    Import-Module -Name AzureRM -MinimumVersion '4.2.1'
    if (! $MFA) {
        $json = Get-ChildItem -Recurse -Include '*@*.json' -Path $KeyPath
        if ($json) {
            Write-Host   "************************************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Host   "************************************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Output " Select the Azure username and Click `"OK`" in lower right-hand corner"
            Write-Output " Otherwise, if this is the first time using this Azure username click `"Cancel`""
            Write-Host   "************************************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Host   "************************************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            $json = $json | select name | Out-GridView -PassThru -Title "Select Azure username or click Cancel to use another"
        }
        if (!($json)) {
            Try {
                $azLogin = Login-AzureRmAccount -ErrorAction Stop
            }
            catch [System.Management.Automation.CommandNotFoundException] {
                Write-Output "Download and install PowerShell 5.1 or PowerShellGet so the AzureRM module can be automatically installed"
                Write-Output "https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-4.2.0#how-to-get-powershellget"
                Write-Output "or download the MSI installer and install from here: https://github.com/Azure/azure-powershell/releases"
                Break
            }
            Save-AzureRmContext -Path ($KeyPath + ($azLogin.Context.Account.Id) + ".json")
            Import-AzureRmContext -Path ($KeyPath + ($azLogin.Context.Account.Id) + ".json")
        }
        else {
            Import-AzureRmContext -Path ($KeyPath + $json.name)
        }
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Output " Select Subscription and Click `"OK`" in lower right-hand corner"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        $subscription = Get-AzureRmSubscription | Out-GridView -PassThru -Title "Choose Azure Subscription"| Select id
        Try {
            Select-AzureRmSubscription -SubscriptionId $subscription.id -ErrorAction Stop
        }
        Catch {
            Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Output " Azure credentials have expired. Authenticate again please."
            Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
            Remove-Item ($KeyPath + $json.name)
            Get-LAAzureConnected
        }
    }
    else {
        Try {
            Login-AzureRmAccount -ErrorAction Stop
        }
        catch [System.Management.Automation.CommandNotFoundException] {
            Write-Output "Download and install PowerShell 5.1 or PowerShellGet so the AzureRM module can be automatically installed"
            Write-Output "https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-4.2.0#how-to-get-powershellget"
            Write-Output "or download the MSI installer and install from here: https://github.com/Azure/azure-powershell/releases"
            Break
        }
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Output " Select Subscription and Click `"OK`" in lower right-hand corner"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        Write-Host   "*********************************************************************" -foregroundcolor "magenta" -backgroundcolor "yellow"
        $subscription = Get-AzureRmSubscription | Out-GridView -PassThru -Title "Choose Azure Subscription"| Select id
        Try {
            Select-AzureRmSubscription -SubscriptionId $subscription.id -ErrorAction Stop
        }
        Catch {
            Write-Output "There was an error selecting your subscription ID"
        }
    }
}