Wednesday, August 16, 2017

Remove-O365PSSession.ps1

Today's script does some basic house cleaning when closing Office 365 Sessions.

As script is simple now code break down unless I receive requests.


 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
<#
.SYNOPSIS
    Remove open O365 PSSessions
.DESCRIPTION
    Remove open O365 PSSessions
.EXAMPLE
    Remove-O365PSSession.ps1
.NOTES
    Created by Chris Lee
    Date April 20, 2017
.LINK 
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Remove-O365PSSession.ps1
    Blogger:http://www.myitresourcebook.com/2017/08/httpsgithubcomclee1107publicblobmastero.html
#>

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

##Close open All O365 product Sessions
Write-Verbose -Message "Removing all PSSessions"
Get-PSSession | Remove-PSSession
Write-Verbose -Message "Disconnecting SharePoint Online"
$ExitPowershell = Read-Host -Prompt "Disconnect from O365 (Will close current Powershell Window) [Y]/N"
If ($ExitPowershell -eq "Y" -OR $ExitPowershell -eq $null -OR $ExitPowershell -eq "")
    {
        stop-process -Id $PID
    }


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

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

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/

Wednesday, August 2, 2017

Install-O365Modules.ps1

Today's post is aimed at setting up your system to connect to all the components of O365.

I feel this script is pretty straight forward and self explaining. If receive requests will come back and do a more in depth post on what is happening.


  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
<#
.SYNOPSIS
    Check for O365 components are present and attempt to install or direct to installers.
.DESCRIPTION
    Check for O365 components are present and attempt to install or direct to installers.
    Installs missing modules for:  
        o Active Directory Online
        o Skype for Business Online
        o SharePointOnline
.EXAMPLE
    Standard execution
    
    Install-O365Modules.ps1
.EXAMPLE
    Verbose messages for troubleshooting installation
    
    Install-O365Modules.ps1 -Verbose
.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/Install-O365Modules.ps1
    Blogger: http://www.myitresourcebook.com/2017/08/install-o365modulesps1.html

#>

[Cmdletbinding()]
Param
(
)

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

## Install O365 Components
    ##Install MSOnline (Azure Active Directory)
        Write-Verbose -Message "Checking for MSOnline (Office 365) Module"
        ## Office 365
            Try 
                {
                    Write-Verbose -Message "Not connected to MSOnline (Azure Active Directory)"
                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                }
            Catch 
                {
                    Write-Verbose -Message "MSOnline Module not found."
                    Write-Verbose -Message 'Check if PowerShell session running in "run as administrator"'
                    If (((whoami /all | select-string S-1-16-12288) -ne $null) -eq $false)
                        {
                            Write-Error 'PowerShell must be ran in "run as administrator to install MSOnline module"'
                            Exit
                        }
                    else 
                        {
                            Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
                            Install-Module MSOnline
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
                                }
                        }
                    }
            
    ##Install SharePoint Online
        Write-Verbose -Message "Checking for SharePoint Online Module"
        ##SharePoint
                    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."
                            $temp = Read-Host "Launch browser to download SharePoint Online Management Shell? [Y]/N"
                            If ($temp -eq $null -OR $temp -eq "" -OR $temp -eq "Y")
                                {
                                    Start-Process https://www.microsoft.com/en-us/download/details.aspx?id=35588      
                                }
                            Else
                                {
                                    Write-Error -Message "Error. Failed to import the module 'Microsoft.Online.SharePoint.PowerShell' because $_" -ErrorAction Stop
                                }
                        }
                        
    ##Install Skype for Business
        Write-Verbose -Message "Checking for Skype for Business Module"
        Try 
            {
                Write-Verbose -Message "$(Get-Date -f o) Importing Module Skype for Business Online Connector"
                Import-Module SkypeOnlineConnector -DisableNameChecking -ErrorAction Stop
            }
        Catch 
            {
                Write-Verbose -Message "SkypeOnlineConnector Module not found."
                $temp = Read-Host "Launch browser to download Skype for Business Online, Windows PowerShell Module? [Y]/N"
                    If ($temp -eq $null -OR $temp -eq "" -OR $temp -eq "Y")
                        {
                            Start-Process https://www.microsoft.com/en-us/download/details.aspx?id=39366    
                        }
                    Else
                        {
                            Write-Error -Message "Error. Failed to import the module 'SkypeOnlineConnector' because $_" -ErrorAction Stop
                        }
            }

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

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

Wednesday, May 17, 2017

Test-O365EncryptedCredentials.ps1

Today's post relies on scripts discussed over the past two weeks:

The purpose of Test-O365EncruptedCrednetials.ps1 is multi staged
  1. load credentials via Get-O365EncryptedCredentials.ps1.
  2. use loaded credentials to execute MSOnline (Active Directory Online) connection to validate credentials (prompt to install needed module if not present)
  3. close PowerShell session when complete to close MSOnline session

COMMENT-BASED HELP

 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
<#
.SYNOPSIS
    Test Connect to Office 365 using saved Office 365 Credentials from Set-O365EncryptedCredentials.ps1
.DESCRIPTION
    Load Credentials via Get-O365EncryptedCredentials.ps1

    Execute MSOnline (Active Directory Online) connection to validate credentials .
    Will prompt to close when complete to close MSOnline session
.PARAMETER Path
    Enter alternate path to save files to, defualt is users local app data
.EXAMPLE
    Test Saved O365 credentials are valid.

    Test-O365EncryptedCredentials.ps1
.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/Test-O365EncryptedCredentials.ps1
    Blogger: http://www.myitresourcebook.com/2017/05/test-o365encryptedcredentialsps1.html
#>
This section of code contains needed information to respond to Get-Help requests.  To view complete help execute string below:
1
Get-Help Set-O365EncryptedCredentials.ps1 -Full
It covers what the script does, provides details of parameters and even examples of how to execute the script. It is good practice to complete this one for yourself and future staff but also for contributing to the PowerShell community.

PARAMTERS


1
2
3
4
5
6
[Cmdletbinding()]
Param
(
    [String]
    $Path = [Environment]::GetFolderPath("LocalApplicationData")
)
This section defines the parameters for the script.

I utilize a single string to define a variable $Path. I further define a default value for the variable, happens to be the executing account's LocalApplcationData folder.
One could override the default by defining the parameter when executing the script like line 1:
1
2
3
4
Set-O365EncryptedCredentials.ps1 -Path "\\server\share\folder

[String]
$Path = "\\Server\share\folder"
Or by updating the default value in the script like lines 3-4.

CODE BREAK

1
2
3
#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################
To reduce novice users from breaking the code I place the above note in my scripts.  Basically unless you know what you are doing or willing to learn how to fix something don't edit the code below this message.


GET CREDENTIALS


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
## Get Credentials
    Write-Verbose -Message "Calling Get-O365EnccryptedCredentials.ps1 to load saved O365 credentials."
    $Cred = Get-O365EncryptedCredentials.ps1 -Path $Path
    If ($Cred.username -eq $null -OR $Cred.username -eq "")
        {
            Write-Host -ForegroundColor Red "Failed to load Encrypted Credentials"
            Write-Error -Message "Failed to load Encrypted Credentials"
            Exit
        }
    Else
        {
            Write-Host -ForegroundColor Green "Encrypted Credentials loaded"
            Write-Verbose -Message "Received from Get-O365EncryptedCredentials:"
            Write-Verbose -Message "Username: $($Cred.UserName)"
        }
  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
  • 
    
    Get-O365EncryptedCredentials.ps1 -Verbose
    
  • Line 3 Executes Get-O365EncryptedCredentials.ps1 with parameter -Path.  Results are returned and stored in variable $Cred via assignment operator equals (=).
  • Line 4 Logical test using If statement to test Credentials loaded from Get-O365EncryptedCredentials.ps1
    • Checks if multi-array $Cred is null or empty via following statements:
      • $Cred.username -eq $null -OR $Cred.username -eq ""
  • Lines 5-9
    • Line 5 Contains the opening bracket ( { ) for If is scriptblock
    • Line 6 Write-Host will print the text with quotes (" ") to screen for user to read.
      
      
      Write-Host -ForegroundColor Red "Failed to load Encrypted Credentials"
      
    • Line 7 Write-Error prints read error message to screen
      
      
      Write-Error -Message "Failed to load Encrypted Credentials"
      
    • Line 8 Exit quits the execution of script
    • Line 9 Contains the closing bracket ( } ) for If is scriptblock
  • Line 10 Declares our else statement, used with If to provide a defined set of code for when If returns as $false.
  • Lines 11-15
    • Line 11 Contains the opening bracket ( { ) for If is scriptblock
    • Line 12 Write-Host will print the text with quotes (" ") to screen for user to read.
      
      
      Write-Host -ForegroundColor Green "Encrypted Credentials loaded"
      
    • Line 13 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
      
      
      Write-Verbose -Message "Received from Get-O365EncryptedCredentials:"
      
    • Line 14 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
      
      
      Write-Verbose -Message "Username: $($Cred.UserName)"
    • Line 15 Contains the closing bracket ( } ) for If is scriptblock

CONNECT TO MICROSOFT ONLINE (MSOLINE)


 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
## Connect of O365 with error checks
    ##Connect MSOnline (Azure Active Directory)
        Write-Verbose -Message "Testing MSOnline (Office 365) Connection with Credentials"
        ## Office 365
            Try 
                {
                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                    Write-Verbose -Message "$(Get-Date -f o) Imported Module MSOline"
                }
            Catch 
                {
                    Write-Verbose -Message "MSOnline Module not found."
                    Write-Verbose -Message 'Check if PowerShell session running in "run as administrator"'
                    If (((whoami /all | select-string S-1-16-12288) -ne $null) -eq $false)
                        {
                            Write-Error 'PowerShell must be ran in "run as administrator to install MSOnline module"'
                            Exit
                        }
                    else 
                        {
                            Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
                            Install-Module MSOnline
                            Try 
                                {
                                    Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                                    Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                                }
                            Catch 
                                {
                                    Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
                                }
                        }
                }
            Try 
                {
                    Write-Verbose -Message "Connecting MSOnline"
                    Connect-MsolService -Credential $cred -ErrorAction Stop
                    Get-MsolDomain -ErrorAction Stop > $null
                    Write-Host -ForegroundColor Green "Connected to MSOnline (Azure Active Directory)"
                    Write-Verbose -Message "Connected MSOnline"
                }
            Catch [Microsoft.Online.Administration.Automation.MicrosoftOnlineException] 
                {
                    Write-Error -Message "Error. Failed to Connect to MSOnline because bad username or password." -ErrorAction Stop
                }
            Catch 
                {
                    Write-Error -Message "Error. Failed to connect to MSOnline because $_" -ErrorAction Stop
                } 
  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2 Comments out text via pound ( # )
  • Line 3 is used for debugging to see what the script is doing.  
  • Line 4 Comments out text via pound ( # )
  • Line 5 Introduce a new PowerShell cmdlet: Try_Catch_Finally
    • Try followed by scriptblock ( {}) will attempt to run code within the script block if successful moves on, if fails will run following catch statement(s) and block(s)
      5
      6
      7
      8
      9
      10
      Try 
         {
            Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
            Import-Module -Name MSOnline -DisableNameChecking -ErrorAction Stop
            Write-Verbose -Message "$(Get-Date -f o) Imported Module MSOline"
          }
      
  • Line 6 Contains the opening bracket ( { ) for Try is scriptblock
  • Line 7 is used for debugging to see what the script is doing.  
  • Line 8 Load MSOnline PowerShell module via Import-Module
    • -Name: targets the module
    • -DisableNameChecking:  suppresses the message that warns you when you import a cmdlet or function whose name includes an unapproved verb or a prohibited character
    • -ErrorAction: overrides the value of the $ErrorActionPreference variable for the current command
      • Stop. Displays the error message and stops executing the command.
  • Line 9 is used for debugging to see what the script is doing.  
  • Line 10 Contains the closing bracket ( } ) for Try is scriptblock
  • Line 11 declares the Catch block if Try block errors
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    Catch 
        {
            Write-Verbose -Message "MSOnline Module not found."
            Write-Verbose -Message 'Check if PowerShell session running in "run as administrator"'
            If (((whoami /all | select-string S-1-16-12288) -ne $null) -eq $false)
                  {
                      Write-Error 'PowerShell must be ran in "run as administrator to install MSOnline module"'
                      Exit
                  }
            else 
                  {
                      Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
                      Install-Module MSOnline
                      Try 
                          {
                              Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                              Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
                          }
                      Catch 
                          {
                              Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
                          }
                   }
        }
    
  • Line 12 Contains the opening bracket ( { ) for Catch's scriptblock
  • Line 13 is used for debugging to see what the script is doing.  
  • Line 14 is used for debugging to see what the script is doing.  
  • Line 15 Logical test using If statement to check if PowerShell console running as Administrator
    
    
    If (((whoami /all | select-string -Pattern S-1-16-12288) -ne $null) -eq $false)
    
    • First, I utilize a cmdline command whoami /all to displays all information in the current access token, including the current user name, security identifiers (SID), privileges, and groups that the current user belongs to.
    • Next, using our handy pipeline ( | ) to pass the results of whoami to Select-String cmdlet
    • Select-String uses Pattern to search passed results for S-1-16-122888
    • We wrap the above commands within " ( ) " and check to confirm results are not equal (-ne) to $null
      • This confirms that results from whoami /all with select-string is not empty
    • Lastly, results of previous commands are evaluated to equal (-eq) $false
  • Lines 16-19 only execute if whoami returns as $false for "run as administrator"
    16
    17
    18
    19
    {
        Write-Error 'PowerShell must be ran in "run as administrator to install MSOnline module"'
        Exit
    
    }
    • Line 16 Contains the opening bracket ( { ) for If's scriptblock
    • Line 17 Write-Error prints read error message to screen
    • Line 18 Exit quits the execution of script
    • Line 19 Contains the closing bracket ( } ) for If's scriptblock
  • Line 20 Declares our else statement, used with If to provide a defined set of code for when If returns as $false.
  • Lines 21-33 only executes if whoami returns as $true for "run as administrator"
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    {
         Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
         Install-Module -Name MSOnline
         Try 
              {
                  Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
                  Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
              }
         Catch 
              {
                  Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
              }
    }
    
    • Line 21 Contains the opening bracket ( { ) for Else's scriptblock
    • Line 22 Write-Host will print the text with quotes (" ") to screen for user to read.
      
      
      Write-Host -ForegroundColor Yellow "Installing MSOnline Module"
      
    • Line 23 Install MSOnline PowerShell module via Install-Module
      
      
      Install-Module MSOnline
    • Line 24 Try
      • Line 25 Contains the opening bracket ( { ) for Try's scriptblock
      • Line 26 is used for debugging to see what the script is doing.
        
        
        Write-Verbose -Message "$(Get-Date -f o) Importing Module MSOline"
        
      • Line 27 Load MSOnline PowerShell module via Import-Module
        1
        Import-Module MSOnline -DisableNameChecking -ErrorAction Stop
        
        • -Name: targets the module
        • -DisableNameChecking:  suppresses the message that warns you when you import a cmdlet or function whose name includes an unapproved verb or a prohibited character
        • -ErrorAction: overrides the value of the $ErrorActionPreference variable for the current command
          • Stop. Displays the error message and stops executing the command.
      • Line 28 Contains the closing bracket ( } ) for Try's scriptblock
    • Line 29 Catch
    • Lines 30-32 only execute if error in Try scriptblock
      • Line 30 Contains the opening bracket ( { ) for Catch's scriptblock
      • Line 31 Write-Error prints read error message to screen
        1
        Write-Error -Message "Error. Cannot import module 'MSOnline' because $_" -ErrorAction Stop
        
      • Line 32 Contains the closing bracket ( } ) for Catch's scriptblock
    • Line 33 Contains the closing bracket ( } ) for Else's scriptblock
  • Line 34 Contains the closing bracket ( } ) for Catch's scriptblock
  • Line 35 Declares an other Try catch series to establish connection to MSOnline
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    Try 
        {
             Write-Verbose -Message "Connecting MSOnline"
             Connect-MsolService -Credential $cred -ErrorAction Stop
             Get-MsolDomain -ErrorAction Stop > $null
             Write-Host -ForegroundColor Green "Connected to MSOnline (Azure Active Directory)"
             Write-Verbose -Message "Connected MSOnline"
         }
    Catch [Microsoft.Online.Administration.Automation.MicrosoftOnlineException] 
         {
             Write-Error -Message "Error. Failed to Connect to MSOnline because bad username or password." -ErrorAction Stop
         }
    Catch 
         {
             Write-Error -Message "Error. Failed to connect to MSOnline because $_" -ErrorAction Stop
         }
    
    • Lines 36-42
      • Line 36 Contains the opening bracket ( { ) for Try's scriptblock
      • Line 37 is used for debugging to see what the script is doing.
        
        
        Write-Verbose -Message "Connecting MSOnline"
        
      • Line 38 Connect to MS Online using encrypted credentials
        
        
        Connect-MsolService -Credential $cred -ErrorAction Stop
        
        • -Credential $cred
          • Use variable $cred created from Get-)365EncryptedCredentials.ps1
        • -ErrorAction: overrides the value of the $ErrorActionPreference variable for the current command
          • Stop. Displays the error message and stops executing the command.
      • Line 39 Check connection by confirming access to domains
        
        
        Get-MsolDomain -ErrorAction Stop > $null
        
      • Line 40 Write-Host will print the text with quotes (" ") to screen for user to read.
        
        
        Write-Host -ForegroundColor Green "Connected to MSOnline (Azure Active Directory)"
        
      • Line 41  is used for debugging to see what the script is doing.
        
        
        Write-Verbose -Message "Connected MSOnline"
        
      • Line 42 Contains the closing bracket ( } ) for Try's scriptblock
  • Line 43 Catch with specific requirement of bad username \ password
    44
    45
    46
    {
       Write-Error -Message "Error. Failed to Connect to MSOnline because bad username or password." -ErrorAction Stop
    }
    
  • Lines 44-46 only execute if Try scriptblock errors and the error is bad username \ password
    • Line 44 Contains the opening bracket ( { ) for Catch's scriptblock
    • Line 45 Write-Error prints read error message to screen
      
      
      Write-Error -Message "Error. Failed to Connect to MSOnline because bad username or password." -ErrorAction Stop
      
    • Line 46 Contains the closing bracket ( } ) for Catch's scriptblock
  • Line 47 Declares general error Catch
    48
    49
    50
    {
        Write-Error -Message "Error. Failed to connect to MSOnline because $_" -ErrorAction Stop
    }
    
  • Line 48-50 only executes if Try scriptblock errors and not related to bad username \ password
    • Line 48 Contains the opening bracket ( { ) for Catch's scriptblock
    • Line 49 Write-Error prints read error message to screen
      
      
      Write-Error -Message "Error. Failed to connect to MSOnline because $_" -ErrorAction Stop
      
    • Line 50 Contains the closing bracket ( } ) for Catch's scriptblock

CLOSE OPEN CONNECTION TO MICROSOFT ONLINE (MSOLINE)


51
52
53
54
55
56
##Close open O365 Sessions
    $ExitPowershell = Read-Host -Prompt "Disconnect from O365 (Will close current Powershell Window) [Y]/N"
    If ($ExitPowershell -eq "Y" -OR $ExitPowershell -eq $null -OR $ExitPowershell -eq "")
        {
            stop-process -Id $PID
        }
  • Line 51 Comments out text via pound ( # )
  • Line 52 Prompt user to close PowerShell session and as such Microsoft Online connection
    
    
    $ExitPowershell = Read-Host -Prompt "Disconnect from O365 (Will close current Powershell Window) [Y]/N"
    
    • Read-Host Prints to display what is in quotes (" ") and waits for user to respond (-prompt is optional)
    • User entered value is saved to variable $ExitPowershell via assignment operator equals (=)
  • Line 53 Logical test to determine if user wants to close PowerShell console
    1
    If ($ExitPowershell -eq "Y" -OR $ExitPowershell -eq $null -OR $ExitPowershell -eq "")
    
    • Multiple formulas utilized to allow for a default [Y]es sperated by -OR
      • $ExitPowershell -eq "Y"
      • $ExitPowershell -eq $null
      • $ExitPowershell -eq ""
  • Line 54 Contains the opening bracket ( { ) for If's scriptblock
  • Line 55 Closes current PowerShell console
    
    
    stop-process -Id $PID
    
    • -ID targets provided process ID
      • Use an Automatic Variable of $PID to pass current PowerShell console Process ID
  • Line 56 Contains the closing bracket ( } ) for If's scriptblock

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

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

Wednesday, May 10, 2017

Get-O365EncryptedCredentials.ps1

Today's post I will be explaining a script the builds on last weeks script Set-O365EncryptedCredentials.ps1.

The purpose of Get-O365EncryptedCredentials.ps1 is to validate the files created in Set-O365EcryptedCredentials.ps1. It can be run in two modes: Test or Pass-Thru.
  • Test Mode will provide feedback on username and if able to load password back into a secure string.
  • Pass-Thru (Default) will pass the loaded credentials back to requesting script.  
    • This will be used in later scripts.

COMMENT-BASED HELP

 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
<#
.SYNOPSIS
    Load saved Office 365 Credentials from Set-O365EncryptedCredentials.ps1 and either pass or test present
.DESCRIPTION
    Check for O365 user and credential files:
        o user.txt - Contains O365 UPN
        o cred.txt - Contains encrypted O365 password

    Load saved Office 365 Credentials from Set-O365EncryptedCredentials.ps1 and either pass or test present
.PARAMETER Test
    Use switch to confirm user name and password loaded from saved credentials
.PARAMETER Path
    Enter alternate path to save files to, defualt is users local app data
.EXAMPLE
    Test for encrypted credential files
    
    Get-O365EncryptedCredentials.ps1 -Test
.EXAMPLE
    Pass encrypted credential to calling script
    
    Get-O365EncryptedCredentials.ps1
.EXAMPLE
    Test for encrypted credential files with verbose messages
    
    Get-O365EncryptedCredentials.ps1 -Test -Verbose
.NOTES
    Created by Chris Lee
    Date May 9th, 2017
.LINK
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Get-O365EncryptedCredentials.ps1
    Blogger: http://www.myitresourcebook.com/2017/05/get-o365encryptedcredentialsps1_9.html
#>
This section of code contains needed information to respond to Get-Help requests.  To view complete help execute string below:

1
Get-Help Get-O365EncryptedCredentials.ps1 -Full
It covers what the script does, provides details of parameters and even examples of how to execute the script. It is good practice to complete this one for yourself and future staff but also for contributing to the PowerShell community.

Parameters

1
2
3
4
5
6
7
8
[Cmdletbinding()]
Param
(
    [switch]
    $Test,
    [String]
    $Path = [Environment]::GetFolderPath("LocalApplicationData")
)
This section defines the parameters for the script.
For this script I utilize two (2) parameters one being a switch type and other a string type.

First, lets cover the switch.  In this script I take advantage of the default value of a switch being $false when not defined.
With that in mind the below statement creates a variable $Test with a value of $false.  This will be used later in the script's logic to skip sections.
1
2
[Switch]
$Test
When a switch parameter is defined in script like following it receives a value of $true:
1
Get-O365EncryptedCredentials.ps1 -Test

Next, I utilize a single string to define a variable $Path. I further define a default value for the variable, happens to be the executing account's LocalApplcationData folder.
One could override the default by defining the parameter when executing the script like line 1:
1
2
3
4
Set-O365EncryptedCredentials.ps1 -Path "\\server\share\folder

[String]
$Path = "\\Server\share\folder"
Or by updating the default value in the script like lines 3-4:

Code Break

1
2
3
#################################
## DO NOT EDIT BELOW THIS LINE ##
#################################
To reduce novice users from breaking the code I place the above note in my scripts.  Basically unless you know what you are doing or willing to learn how to fix something don't edit the code below this message.

Check for User File

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
##Load User name
    Write-Verbose -Message "Checking for user file"
    IF (!(Test-Path -Path "$Path\O365user.txt"))
        {
            Write-Host -ForegroundColor Red "No user file found"
            Write-Error -Message "No user file found"
            Exit
        }
    else
        {
            Write-Host -ForegroundColor Green "User File found"
            $AdminName = Get-Content "$Path\O365user.txt"
        }
  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
  • 1
    Get-O365EncryptedCredentials.ps1 -Verbose
    
  • Line 3  is using several logic tests an If statement along with Test-Path, and a modifer the exclamation mark (!).
    • Let's check out Test-Path first:
      • Checks to determine if defined path or file does exists to return $true else it returns $false
    • Next we have the exclamation mark (!):
      • This is a logic operator that changes the test to opposite (can also be represented as "-not")
      • In script changes Test-Path logic above to now read:
        • Checks to determine if defined path or file does not exists to return $true else it returns $false
    • Now let's pull it all together in our Ifstatement:
      1
      IF (!(Test-Path -Path "$Path\O365user.txt"))
      
      • In this scenario our logic test is checking that the defined file "O365user.txt" does not exist.  If $true will execute following code inside{}otherwise execute code within else's {}
  • Line 4-8 only execute when If statements does not find defined file.
    • Line 4 Contains the opening bracket ( { ) for If's scriptblock
    • Line 5
      • Write-Host will print the text with quotes (" ") to screen for user to read.  
        1
        Write-Host -ForegroundColor Red "No user file found" 
        • The parameter -foreground allows color to be defined, in this case the color is red.
    • Line 6
      • Write-Error prints read error message to screen
      • 1
        Write-Error -Message "No user file found"
        
    • Line 7
      • Exit quits the execution of script
    • Line 8 Contains the closing bracket ( } ) for If's scriptblock
  • Lines 9-13 only executes when If statement does find the defined file
    • Line 9 Declares our else statement, used with If to provide a defined set of code for when If returns as $false.
    • Line 10 Contains the opening bracket ( { ) for else's scriptblock
    • Line 11 
      • Write-Host will print the text with quotes (" ") to screen for user to read.  
        1
        Write-Host -ForegroundColor Green "User File found"
        
        • The parameter -foreground allows color to be defined, in this case as color green
    • Line 12 Uses Get-Content to read lines from "O365user.txt" and save them to $AdminName varaible via assignment operator equals (=)
      1
      $AdminName = Get-Content "$Path\O365user.txt"
    • Line 13 Contains the closing bracket ( } ) for else's scriptblock

Check for Encrypted password file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
##Load Encrypted password
    Write-Verbose -Message "Checking for required password file"
    IF (!(Test-Path -Path "$Path\O365cred.txt"))
        {
            Write-Host -ForegroundColor Red "No password file found"
            Write-Error -Message "No password file found"
            Exit
        }
    else
        {
            Write-Host -ForegroundColor Green "Password File Found"
            $Pass = Get-Content "$Path\O365cred.txt" | ConvertTo-SecureString
        }
  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
  • 1
    Get-O365EncryptedCredentials.ps1 -Verbose
    
  • Line 3  is using several logic tests an If statement along with Test-Path, and a modifer the exclamation mark (!).
    • Let's check out Test-Path first:
      • Checks to determine if defined path or file does exists to return $true else it returns $false
    • Next we have the exclamation mark (!):
      • This is a logic operator that changes the test to opposite (can also be represented as "-not")
      • In script changes Test-Path logic above to now read:
        • Checks to determine if defined path or file does not exists to return $true else it returns $false
    • Now let's pull it all together in our If statement:
      1
      IF (!(Test-Path -Path "$Path\O365cred.txt"))
      • In this scenario our logic test is checking that the defined file "O365cred.txt" does not exist.  If $true will execute following code inside{}otherwise execute code within else's {}
  • Line 4-8 only execute when If statements does not find defined file.
    • Line 4 Contains the opening bracket ( { ) for If is scriptblock
    • Line 5
      • Write-Host will print the text with quotes (" ") to screen for user to read.  
        1
        Write-Host -ForegroundColor Red "No password file found" 
        • The parameter -foreground allows color to be defined, in this case the color is red.
    • Line 6
      • Write-Error prints read error message to screen
      • 1
        Write-Error -Message "No password file found"
        
    • Line 7
      • Exit quits the execution of script
    • Line 8 Contains the closing bracket ( } ) for If is scriptblock
  • Line 9 Declares our else statement, used with If to provide a defined set of code for when If returns as $false.
  • Lines 10-13 only executes when If statement does find the defined file.
    • Line 10 Contains the opening bracket ( { ) for else is scriptblock
    • Line 11 
      • Write-Host will print the text with quotes (" ") to screen for user to read.  
        1
        Write-Host -ForegroundColor Green "Password File found"
        
        • The parameter -foreground allows color to be defined, in this case as color green
    • Line 12 Introduces a new cmdlet "ConvertTo-SecureString" so lets walk through this line.
      1
      $Pass = Get-Content "$Path\O365cred.txt" | ConvertTo-SecureString
      
      • As used previously Get-Content reads lines from files (in this case O365cred.txt)
      • Next we use pipeline ( | ) to feed output of Get-Content to ConvertTo-SecureString
      • ConvertTo-SecureString converts the encrypted standard strings from Get-Content to a secure strings
      • Lastly we use the assignment operator equals (=) to assign the secure string value to our variable $Pass
    • Line 13 Contains the closing bracket ( } ) for If is scriptblock

CREATE CREDENTIAL VARIABLE


1
2
3
## Create Cred variable
    Write-Verbose -Message "Creating Credential varialble from files"
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
  • 1
    Get-O365EncryptedCredentials.ps1 -Verbose
    
  • Line 3 Uses New-Object to make PSCredential from the provided username and password and then save to $Cred variable
    • -typename defines the type of object to be created
      • In this case we are defining System.Management.Automation.PSCredential
    • -arguementlist list of items to be used in creation of new object
      • In this case we use previous defined variables: $AdminName and $Pass
    • assignment operator equals (=) to assign the PSCredential value to our variable $Cred

TEST OF PASS-THRU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
## Check if testing or passing credentials
    Write-Verbose -Message "Check if in test mode or pass-thru mode"
    If ($test)
        {
            Write-Verbose -Message "Test mode"
            ## Display loaded credentias
                Write-Host "Username: $($Cred.UserName)"
                Write-Host "Password: $($Cred.Password)"
        }
    Else 
        {
            Write-Verbose -Message "Pass-thru mode"
            ## Passing Cred variable to other script
                $Cred
        }

  • Line 1 Comments out text via pound ( # ) and used as a section marker
  • Line 2  is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
  • 1
    Get-O365EncryptedCredentials.ps1 -Verbose
  • Line 3 uses an If statement to check value of $test
  • Lines 4-9 only execute when $test is $true
    4
    5
    6
    7
    8
    9
    {
        Write-Verbose -Message "Test mode"
        ## Display loaded credentias
           Write-Host "Username: $($Cred.UserName)"
           Write-Host "Password: $($Cred.Password)"
    }
    
    • Line 4 Contains the opening bracket ( { ) for else is scriptblock
    • Line 5 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
    • 1
      Get-O365EncryptedCredentials.ps1 -Verbose
    • Line 6 Comments out text via pound ( # ) and used as a section marker
    • Line 7 Write-Host will print the text with quotes (" ") to screen for user to read.
      1
      Write-Host "Username: $($Cred.UserName)"
      
      • Use $( ) Subexpression operator to call $Cred arrays UserName value
    • Line 8 Write-Host will print the text with quotes (" ") to screen for user to read.
      1
      Write-Host "Username: $($Cred.Password)"
      
      • Use $( ) Subexpression operator to call $Cred arrays Password value
    • Line 9 Contains the closing bracket ( } ) for If is scriptblock
  • Line 10 Declares our else statement, used with If to provide a defined set of code for when If returns as $false.
  • Lines 11-15 only execute when $test is $false
    11
    12
    13
    14
    15
    {
       Write-Verbose -Message "Pass-thru mode"
       ## Passing Cred variable to other script
          $Cred
    }
    
    • Line 11 Contains the opening bracket ( { ) for else is scriptblock
    • Line 12 is used for debugging to see what the script is doing.  Verbose messages will only be displayed when script is executed with the Verbose parameter, like such:
    • 1
      Get-O365EncryptedCredentials.ps1 -Verbose
    • Line 13 Comments out text via pound ( # ) and used as a section marker
    • Line 14 Calls $Cred to pass back to calling script
    • Line 15 Contains the closing bracket ( } ) for If is scriptblock

Full script can be accessed from following link:
Further reference links for PowerShell cmdlets used can be found on following post:

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