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/

Friday, May 5, 2017

PowerShell MSDN references used

This post will be updated with ongoing record of Microsoft's MSDNs referenced in my blog.

Github Setup

For my current PowerShell series I am using several tools.

First, there is Git as I am posting code to a public GitHub.  For this process I have two options Git via CLI and Git via GUI.

Git CLI:



Git GUI:

  • For the GUI side I utilize GitKracken. 
  • It is OS agnostic which is nice when I have access to both Windows, Linux and Mac platforms. 
Second, is the text editor I have recently switched to:Visual Studio Code (https://code.visualstudio.com/).  Visual Studio Code is OS agnostic like GitKracken offering installation on Linux, Windows, and Mac.  In addition there are "Extensions" to add additional features to the base program. Currently I am using PowerShell extension to allow writing code and executing in one window (similar to PowerShell ISE) but also supports Git commands to quickly commit and push to current Repo.   I have barely begun to learn Visual Studio Code and imagine it can do much more then what I currently use it for.

Wednesday, May 3, 2017

Set-O365EncryptedCredentials.ps1

The purpose of Set-O365EncryptedCredentials.ps1 is to collect credential information for connecting to Office 365 (O365) and save them into local files (O365user.txt / O365cred.txt) to be called in future scripts.
  • O365user.txt - Text file containing plain text username for O365 access
  • O365cred.txt - Text file containing encrypted password for O365 access

Note: Links to Full script and MSDN pages of used commands at end of post.

COMMENT-BASED HELP


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<#
.SYNOPSIS
    Create User and Password files for future use
.DESCRIPTION
    Create following files for use in auto login for O365:
        o user.txt - Contains O365 UPN (Optional)
        o cred.txt - Contains encrypted O365 password (Required)
.PARAMETER Path
    Enter alternate path to save files to, defualt is users local app data
.EXAMPLE
    Set-O365EncryptedCredentials.ps1
.NOTES
    Created by Chris Lee
    Date April 20, 2017
.LINK 
    GitHub: https://github.com/clee1107/Public/blob/master/O365/Set-O365EncryptedCredentials.ps1
    Blogger: http://www.myitresourcebook.com/2017/05/set-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.


CREATE USER FILE


1
2
3
##Create User account if provided
    Read-Host -Prompt "Enter your tenant UPN" `
        | Out-File "$Path\O365user.txt"
  • Line 1 This line comments out and places a marker stating what the following lines do
  • Line 2 Read-Host Prints to display what is in quotes (" ") and waits for user to respond (-prompt is optional
    • Note the backtick ( ` ) at the end, this is a special escape character called a line continuation.  It allows long strings to be broken onto several lines.  I utilize this to break long strings that utilize pipeline ( | ) or become to long.
  • Line 3 Is a continuation of line 2 thanks to the backtick ( ` ).  To start we have a pipeline ( | ) operator then Out-File
    • Pipeline ( | ) allows the output of previous command to be used as input of following command.
      • In this casethe output of line 2's Read-Host (user's input) is passed to line 3's Out-File
    • Out-File sends output to a file
      • In this case the output of line 2's Read-Host (user's input) is passed to line 3's Out-File to be written to file O365user.txt in the defined path.

CREATE ENCRYPTED PASSWORD FILE


1
2
3
4
##Create Password
    Read-Host -Prompt "Enter your tenant password" -AsSecureString `
        | ConvertFrom-SecureString `
        | Out-File "$Path\O365cred.txt"
  • Line 1 This line comments out and places a marker stating what the following lines do
  • Line 2 Read-Host Prints to display what is in quotes (" ") and waits for user to respond
    • -prompt is optional as PowerShell assumes it's presence
    • -AsSecureString masks user input on the screen with asterisks (*) and stores the input as Securestring object (System.Security.SecureString)
    • Note the backtick ( ` ) at the end, this is a special escape character called a line continuation.  It allows long strings to be broken onto several lines.  I utilize this to break long strings that utilize pipeline ( | ) or become to long.
  • Line 3 Is a continuation of line 2 thanks to the backtick ( ` ).  To start we have a pipeline ( | ) operator then ConvertFrom-SecureString followed by another backtick ( ` )
    • Pipeline ( | ) allows the output of previous command to be used as input of following command.
      • In this case the output of line 2's Read-Host (user's input) is passed to line 3's ConvertFrom-SecureString
    • ConvertFrom-SecureString tales the SecureObject from line 2's Read-Host and converts it to an encrypted standard string (System.String)
    • Backtick ( ` ) provide line continuation to line 4
  • Line 4 Continues from line 3's backtick ( ` ).  Here we use the pipeline ( | ) operator again to send output to the Out-File cmdlet
    • Pipeline ( | ) allows the output of previous command to be used as input of following command.
      • In this case the output of line 2's Read-Host (user's input) is passed to line 3's Out-File
    • Out-File sends output to a file
      • In this case the output of line 2's Read-Host (user's input) is passed to line 3's Out-File to be written to file O365user.txt in the defined path.


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/

Monday, May 1, 2017

PowerShell: O365 Series

Over the coming weeks I will post some scripts I have created out of need at my current employer for connecting and managing Office 365.

Chris

Listing of Scripts so far (8/1/2017):