Monday, January 20, 2014

Microsoft Virtual Academy: PowerShell M08


To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioWUlmOXVBYlJEWU0/edit?usp=sharing)

Module 8 "Automation in scale: remoting" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 9 slides.

Overview:
  • Remoting
  • Sessions
  • Remote CMDLETs
  • Measure execution speed
Remoting

    As covered in past module/posts we can execute CMDLETs on remote systems using the Invoke-Command / ICM.  Somethings to understand about this process.


  • When executed command sent to remote system to establish PowerShell session.
    • Involves creating TCP connection, PowerShell session each time the ICM command is used.
  • This is inefficient for many reasons:
    1. Resources wasted to create and tear down PowerShell session on remote system for each ICM execution
    2. Since each ICM is it's own session nothing remains in memory after tear down.  This causes problems for automation.
To get around the limitations and work more efficiently remote PowerShell sessions are allowed.  It allows the remote start of a PowerShell session that will remain alive until closed. This allows for data to be passed through following CMDLETs.



Sessions

    A PowerShell session allows the execution of CMDLETs and usage of local memory for data/variables.  A session can be created by opening local PowerShell shell or through CMDLET New-PSSession (Sessions can be local or remote).

New-PSSession -Computername [DC1]
     Opens new session with remote system (DC1)

To view current live/open sessions we use the following:
Get-PSSession
 Id       Name            ComputerName    State         ConfigurationName         Availability
 --        ----                  ------------                  -----            -----------------                        ------------
  4       Session4      cutie                        Opened     Microsoft.PowerShell     Available
  5       Cutie             cutie                         Opened     Microsoft.PowerShell     Available


Remote CMDLETS
    
Enabling Remoting


Monday, January 13, 2014

Microsoft Virtual Academy: PowerShell M07 (Part 3)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview
Output to Screen

 PowerShell offers a few ways to provide output to the screen from your script.   The most common is Write-Host as it provides the ability to format colors.  There are some issues with using Write-Host as it breaks the ability to pipe.  To maintain the pipeline use Write-Output.  To provide you color text they have provided us with Write-Error / Write-Warning / Write-Debug.

Write-Host
    Allows output to the screen to be formatted.  Remember this breaks pipeline usage and is not best practice in a script.

Write-Host "Hello" -Foregroundcolor red -BackGroundColor green
         Sets colors
   
     Outputs:Hello
   

Write-Output
   Way to output to screen with out breaking pipeline.

Write-Output "Hello"

    Outputs: Hello

Write-Error / Write-Warning / Write-Debug
    All three of these cmdlets use the default PowerShell scheme to maintain quick recognition.

Write-Warning "Help, Help"

    Outputs: Help, Help

Write-Error "Doom, Doom"

     Outputs: Doom, Doom

Check out the rest of this segment:
Part 1: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part1.html
Part 2: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part2.html

Microsoft Virtual Academy: PowerShell M07 (Part 2)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview

Variables

   Variables are a huge part the power o f PowerShell.  Variables can store not just numerical or string for output but also cmdlets for recall later, executed against, or even run method if supported.  A variable is defined by $ and can be recalled by $name.  Variables are not saved after shell or session is closed.  Check out the slides for how to use variables and quotes.

Example of string for output:
$myvar="HelloWorld"
        Sets HelloWorld into variable myvar
$myvar
        To call variable we enter it's name
HelloWorld
        Value returned from call

Example of numerical 
$myvar="1354"
        Sets HelloWorld into variable myvar
$myvar
        To call variable we enter it's name
1354
        Value returned from call

Example of cmdlet:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar
        Calls variable myvar which executes stored cmdlet Get-Service bits
Status          Name         DisplayName
------          ----         -----------
Running         bits         Background Intelligent Transfer Ser...
        Results of cmdlet

Example of cmdlet executed against:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar | gm
        Calls variable myvar which executes stored cmdlet Get-Service bits and runs through pipe get-member
                 TypeName: System.ServiceProcess.ServiceController

Name                                                  MemberType                  Definition
----                                                        ----------                            ----------
Name                                                  AliasProperty                 Name = ServiceName
RequiredServices                            AliasProperty                  RequiredServices = ServicesDependedOn
Disposed                                           Event                                System.EventHandler Disposed(System.Object, System.EventArgs)
Close                                                  Method                             void Close()
Continue                                            Method                              void Continue()
....
        Results of cmdlet

Example of cmdlet method:
$myvar=Get-Service bits
        Sets cmdlet Get-Service to variable myvar
$myvar.status
        Calls variable myvar which executes stored cmdlet Get-Service bits but only outputs Status
Running
        Results of cmdlet

  Variables are also not limited to a single word or continues string for a name.  By using the brackets {} you can use phrases as the variable name.
${This is a test}=4
         Sets value of 4 to variable This is a test
${This is a test}
        Call variable This is a test
4
        Results

Read-Host
  Now it is all nice that we can static set a variable but what if I want to ask the user for information (name/amount/etc).  To do this we use:

Read-Host  "Message here"

To save this to a variable we just append $var = to the front of string as below:

$myvar = Read-Host "Enter Computer name:"
        Prompts the user to enter a value and saves it to variable myvar

Check out the rest of this segment:
Part 1: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part1.html
Part 3: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part3.html

Microsoft Virtual Academy: PowerShell M07 (Part 1)

Here we are module 7 only two more.  This is a short segment but lots of information.  To keep things short I have split it among three posts.  Check the Overview to see what is covered under this post.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 7: "Getting prepared for automation" consists of 2 video segments totaling ≈ 26 minutes along with a PowerPoint of 12 slides.

Overview
Execution Policy

   The execution policy is your safety net when it comes to PowerShell. The requirement for execution policy to allow a script to run is digitally signed and must be trusted.  This is different from VB scripts that just required them to be signed. With all the power that you have in scripts it is the execution policy that prevents malicious attacks.  By default it is set to restricted (on 2012R2 believe it is now RemoteSigned). To see what level your execution policy is at run following:

 Get-ExecutionPolicy 

   There are six levels of security: Restricted, Unrestricted, AllSigned, RemoteSigned, Bypass, and Undefined.  For more details on levels check out TechNet article: http://technet.microsoft.com/en-us/library/hh849812.aspx.  Note of warning avoid using Unrestricted and Bypass. For this module we focus in on RemoteSigned and AllSigned.  RemoteSigned is best for users starting out as it will allow an local created scripts to be ran without being signed, whereas AllSigned will require all scripts to be signed.

   Execution policy can be set through group policies (GPO) or at individual systems.  For GPO instructions check out this TechRepublic article: http://www.techrepublic.com/blog/the-enterprise-cloud/set-the-powershell-execution-policy-via-group-policy/ for individual systems you would execute following code:

 Set-ExecutionPolicy “[desired level]” 

Eample:
 Set-ExecutionPolicy “remotesigned” 

Signing Scripts

   As you work on creating scripts and securing your network you will at some point move to AllSigned.  This will require all scripts to be signed including the ones you create on a local system.  The following will walk you through how to sign a script.

Create
   To start you first need a self-signed certificate to use for signing.

New-SelfSignCertificate
    v3 or higher (Version 2 or non Win8/2k12 will use makecert.  More details here: http://www.hanselman.com/blog/SigningPowerShellScripts.aspx)

Load
    Now we need to find this self-signed certificate and load for future use.

Get-PSDrive
  Displays drives available during PowerShell session

Dir Cert:\CurrentUser -Recurse -CodeSigningCert -OutVariable a
  Pulls all certs created for current users with code signing rights and assigns them to variable a

$cert = $a[0]
  Takes and assigns first certificate from variable a to variable cert

Sign
   Now that we have a certificate loaded into $cert we can sign our scripts using the following code:

Set-AuthenticodeSignature -Certificate $cert -FilePath [pathtoscript]

Example:
Set-AuthenticodeSignature -Certificate $cert -FilePath C:\_scripts\hello.ps1

Results
   Now that we have a signed script set execution policy to all signed.  When you try to run you are prompted with choices:

  • Never Run
    • Does not run and adds certificate to blocked or untrusted list
  • Do not run
    • Does not run and does nothing with cert
  • Run Once
    • Runs but does nothing with cert
  • Always Run
    • Runs and adds certificate to trusted/allowed list
Check out the rest of this segment:
Part 2: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part2.html
Part 3: http://cleeit.blogspot.com/2014/01/MVA-powershell-m07-part3.html

Tuesday, January 7, 2014

PowerShell: Connectivity Monitor with Email Alert

Recently saw a post on Spiceworks that caught my eye. A poster was looking to improve a batch script by using PowerShell.  The purpose of this batch script was to test connectivity of a site based on ping.  The script worked as needed but was giving false negatives.  To resolve the poster wanted to have it test ping twice.

Below is the PowerShell script that Martin Pugh (Martin9700) provided, the thread can be viewed here: http://community.spiceworks.com/topic/427943-ping-test-script?page=1#entry-2863765

 # +-----------------------------------------------------------------------------------  
 # | File : Connectivity Monitor with Email Alert.ps1                       
 # | Version : 1.01                       
 # | Purpose : Provided CSV of IPs will test for connectivity (see comments at end)  
 # |           Ping list of IPs for connectivity  
 # |           If failed wait and repeat ping  
 # |           If failed 2nd time send alert email  
 # |        
 # | Based on: Martin Pugh (Martin9700) SpiceWorks thread  
 # |      http://community.spiceworks.com/topic/427943-ping-test-script?page=1#entry-2863455  
 # +-----------------------------------------------------------------------------------  
 # | Maintenance History                        
 # | -------------------                        
 # | Name      Date    Version C/R Description      
 # | ----------------------------------------------------------------------------------  
 # | Martin Pugh   2014-01-07   1.01     Initial scirpt build  
 # +-----------------------------------------------------------------------------------  
   
 ###SETUP START###  
      #Path to file with IP addresses  
           $Path = "[PATHTOYOURIPLISTCSVDOCUMENT]"  
      #SMTP Server to be used  
           $smtp = "{YOURSMTP]"  
      #"From" address of the email  
           $from = "ServerReports@{YOURDOMAIN].com"  
      #Enter Admin Email Address  
           $to="[YOURADMIN]@[YOURDOMAIN].com"  
 ###SETUP END###  
   
 ###PROGRAM START###  
      ForEach ($IP in (Import-CSV $Path))  
           {If (-not (Test-Connection $IP.Address -Quiet -Count 2))  
                {Start-Sleep -Seconds 2  
                     If (-not (Test-Connection $IP.Address -Quiet))  
                          {#Send Alert Email  
                               Send-MailMessage -To $to -From $from -Subject "Problem with $($IP.Location)" -Body "Problem detected with site at $($IP.Location), $($IP.Address)" -SmtpServer $smtp  
                          }  
                }  
           }  
 ###PROGRAM END###  
   
 ############################REMOVE AFTER SETUP##############################################  
 ######CSV file needs to have following format######  
 #Location,Address  
 #Sitename1,x.x.x.x  
 #Sitename2,x.x.x.x  

Monday, January 6, 2014

Microsoft Virtual Academy: PowerShell M06

Well it has been a hectic holiday period but back to work, I am behind on getting my notes converted into posts.  We should be finishing up this series by the end of Jan.

To start your own learning check out Microsoft Virtual Academy:
(http://www.microsoftvirtualacademy.com/training-courses/getting-started-with-powershell-3-0-jump-start?o=3276#?fbid=aVs9FfAH2DJ)
(rewritten based on my notes available here: https://drive.google.com/file/d/0B1fwreWrAZioQ28xTmx0d29HUzQ/edit?usp=sharing)

Module 6 "The PowerShell in the shell: remoting" consists of 3 video segments totaling ≈ 55 minutes along with a PowerPoint of 11 slides.

Overview:
  • Remoting
    • Security
    • Enabling Remoting
    • Remoting
      • One-to-One
      • One-to-Many
  • PowerShell via web
Security

    To start lets get the security stuff out of the way.  PowerShell uses Kerboros to encrypt all transmissions from the terminal to the remote system. It can be further secured with the use of SSL.  This allows for easier firewall management as it uses a single port.  

Enable Remoting

    Two ways to enable PowerShell remoting.  First is to log on to each server/system and execute:

Enabling Remoting

   This is time and energy consuming.  The second way is more efficient and that is with use of GPOs.  Check out the links below for more details:

How To Enable Powershell Remoting - Spiceworks - Martin9700
      http://community.spiceworks.com/how_to/show/18512-how-to-enable-powershell-remoting


Enable and configure Windows PowerShell Remoting using Group Policy - blog.powershell.no
     http://blog.powershell.no/2010/03/04/enable-and-configure-windows-powershell-remoting-using-group-policy/

Remoting

    Once you have enabled PowerShell Remoting there are two ways to manage systems: one-to-one and one-to-many. As you may guess that is control system to remote systems.  Depending on how many systems you are controlling will impact the way PowerShell interacts with them.  Remember when remoting the work is completed on remote system and not on local/management system.

One-to-One
   This process allows you to interact with the remote system similar to being directly logged on. To access remote system use:

Enter-PSSession -ComputerName [computername]

Example:
Enter-PSSession -ComputerName DC


Once you have access to the system you PowerShell prompt will change to resemble following: [computername]: PS C:\>.  You can now run cmdlets as you would on local system.  This is handy if you need full access to a system can't access directly.

One-to-Many
   This process accesses multiple systems and returns results as objects.  To execute use the following:
      
Invoke-Command -ComputerName [computernames seperated by comma] {cmdlet} 

Example:
Invoke-Command -ComputerName dc,dc1 {Get-EventLog -LogName System  -new 3}



PowerShell via web
   Want to or need the ability to access PowerShell via the web?  How about from mobile devices?  Well they thought of this and have provided a solution for version 3 and higher.

   To accomplish this we will install Windows PowerShell Web Access (pswa).  This consists of roughly three commands to complete.   It will install IIS and .Net 4.5 if not already installed.  To start we first run:

Install-WindowsFeature WindowsPowerShellWebAccess
         (Installs IIS and .Net 4.5)

Install-PSWAWebApplication
          (Sets up and cinfigures IIS for pswa)

Add-PSWAAuthrizationRule -ComputerName [name] -username [users] -configurations
          (More details available here:http://technet.microsoft.com/en-us/library/jj592890.aspx)

   Once completed you (and firewall configured correctly) you can browse to your new IIS site and access PowerShell through HTTPS.

Resources mentioned in module:
   Secrets of PowerShell: Remoting
       https://github.com/PowerShellOrg/ebooks/tree/master/Remoting