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/

5 comments: