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/

No comments:

Post a Comment