Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Thursday, September 19, 2013

Add Windows Features to Remote Servers

This morning I had a question come in on LinkedIn about installing the SNMP service on 20 remote servers.  The first person who responded recommended using Enable-PSRemoting on all servers and the downloading some tools from Sysinternals.  He was on the right track.  The problem is that process would require either traveling to the remote sites or providing admin credentials to local users to do it for him.   Also, the full power of PowerShell remoting is not utilized since the instructions were to utilized other software.

A simpler solution would be to enable PowerShell Remoting via Group Policy :(http://mctexpert.blogspot.com/2011/03/enable-powershell-v2-remote-management.html).

Next, you need to create a session to your remote servers.


$Session = New-PSSession –ComputerName SVR1, SVR2, SVR3

Using the Invoke-Command cmdlet, you can execute commands on the remote machines. You first need to import ServerManager on the remote machines (Unless your remote servers run PowerShell V3) and then add the feature. This importing of ServerManager is actually being done on the remote servers. Look carefully, that is a semi colon “;” after ServerManager.

Invoke-Command –Scriptblock {Import-Module ServerManager; Add-WindowsFeature “SNMP-Services” –IncludeAllSubFeatures} –Session $Session

Monday, September 9, 2013

How to Create About_ Conceptual Help Files for Your Modules

First off, I want to thank Gaby Kaplan from Microsoft and the PowerShell team for helping find this path to success. 

I needed to find a very simplistic way of creating conceptual help files for my PowerShell modules.  Some of this code gets sent to my students after my PowerShell classes and I like to provide as much information as I can.  You will recognize conceptual help files because they start with About_.  So, here we go.

Step 1. Create a text file in the same directory as your script module.  Mt module is stored in my user account’s Documents\WindowsPowerShell\Modules\PSV3. PSv3 is the name of the module that I will be sending to my class.

Step 2. Name the file correctly. The syntax is About_NameOfYourConcept.help.txt.

Step 3. Add the content to the text file and save it.

Step 4. Import the module.  Whoa!!!! Wait a second. in PowerShell V3, we had auto loading of all of our modules.  That is true and this is what kind of messed me up a bit.  Thanks to Gaby’s time and patience, she was able to find the reason for this.  You will need to import the module manually. In PowerShell V4, you do not.  This is what the PowerShell Project Manager sent to Gaby:

Prior to PowerShell 4.0, the module must be imported into the current session in order for Get-Help to find the topic. This is because Get-Help only looks in $pshome and loaded module folders for About topics. We improved this in PowerShell 4.0 so that the module no longer needs to be imported / loaded. Get-Help will look in all module folders under PSModulePath for a matching About topic.

The PowerShell PM also noted that if you store your help file in the $PSHOME folder, it will be deleted during servicing.

So, in walks Hyper-V and some virtualization.  Utilizing a preview copy of Windows 8.1, I gave this a try.  Like I said, preview copy.  This capability is not there just yet, so I’m going to wait for the full release.

To see what else is new in V4, check out What’s New in PowerShell.

If you would like to give the Windows 8.1 preview a try (as well as PowerShell V4) follow this link to Microsoft.

Friday, September 6, 2013

Odd Behavior When creating BAT Files with PowerShell

Just the fact the I’m using PowerShell to create BAT files is odd enough.  This pesky little problem cost me many hours of precious time.  Essentially, I’m writing some PowerShell code to look at some BAT files and then reconfigure them according to my scripts logic.  That all works flawlessly.  The problem is some extra bits added to the beginning of each line. I was using the Out-File cmdlet to save the new paths to the BAT file.  Take a look at this one line:

"Dir" | Out-FileLiteralPath "J:\PSTest.bat" 

 

Simple enough.  It created a BAT file call PSTest with only one command, “DIR”.  This is what happens when you run it.

image

What is the mysterious character in front of the “D”?  I tried to implement this in several different ways.  File redirection using “>>” did not work.  It yielded the same results.  I also tried the –encoding parameter of Out-File.  Same result. Using Get-Content in PowerShell, Type in DOS, or even opening the file in Notepad would produce a normal looking file.  No signs of the mysterious character. I finally settled on Add-Content.

Add-Content will add a line of text to a text file.  Since this file would be changing often, I had to include code that would test for the existence of the file and remove it if it was already there:

# See is a configuration file already exists.

# Make sure it is empty.

If (Test-Path -Path "J:\PSTest.bat")

{

    Remove-Item "J:\PSTest.bat"

}

 

Now I can add as many commands as I want by calling Add-Content.

Add-Content -Path "J:\PSTest.bat" -Value "DIR"

 

Now the mysterious character is no longer present and the batch file will execute normally.

Monday, September 2, 2013

Comparing Text Files with PowerShell

Being a Microsoft Certified Trainer, I work with a lot of different clients spread over 11 different time zones.  I sometimes need a little help when it comes to looking at contracts from my clients.  The old saying “All is fair in love and business” is something that all business owners needs to remember.  Fortunately for me, from client to client, contracts are fairly identical.  I still like to look for anything that has changed from a previous contract with a client, but this can be time consuming. 

Below is a little script that I use to highlight any changes.  I just simply save the contents of the contracts into a text file and feed the new contract and the previous one into this script.  This script will highlight any differences in each line.  This helps to quickly direct my attention where it needs to be.  In most cases, the contracts are 99% identical from one to the other.  This just helps to make sure that I do not miss that 1%.

One thing to note is the use of Write-Host in this code.  The design of the code is note to be used in the PowerShell pipeline.  It is to be displayed utilizing colors.

Function Compare-Contract

{

[cmdletBinding()]

Param (

    $Previous = "C:\Users\JASON\Documents\PowerShell\InDevelopment\CompareContract\Previous.txt",

    $Current = "C:\Users\JASON\Documents\PowerShell\InDevelopment\CompareContract\Current.txt"

)

 

 

    # Function: Write-Line

    # Writes the characters out one by one.  Green if they match, red if they do not.

    # The LoneLine and ShortLine allows for any lines that have extra

    # Characters in them to be marked in red.

    Function Write-Line

    {

        Param ($LongLine, $ShortLine)

        $Y = $LongLine.Count

 

        Try

        {

            For ($X = 0;$X -lt $Y; $X++)

            {

                If($LongLine[$X] -eq $ShortLine[$X])

                {

                    Write-Host "$($LongLine[$X])" -NoNewline @Color0

                }

                Else

                {

                    Write-Host "$($LongLine[$X])" -NoNewline @Color1

                }

               

            }

        }

        Catch

        {Write-Host "$LongLine[$X]" -NoNewline @Color1}

 

        # Adds a carriage return to the line.

        Write-Host ""

 

    } # End: Function Write-Line

 

    # Read the content of the text files.

    $Previous = Get-Content $Previous

    $Current = Get-Content $Current

 

    # Split the contracts on each line.  This helps to reduce

    # the false positives.

    $Prev = $Previous.Split("`n")

    $Curr = $Current.Split("`n")

   

    # Color splats used to help clarify what I need to look at.

    $Color0 = @{ForegroundColor="Green";BackgroundColor = "DarkBlue"}

    $Color1 = @{ForegroundColor="Red";BackgroundColor = "DarkRed"}

    $Color2 = @{ForegroundColor="Cyan";BackgroundColor = "DarkBlue"}

    $Color3 = @{ForegroundColor="Magenta";BackgroundColor = "DarkBlue"}   

    

    # Lets you know if any lines were added or removed between contracts.

    Write-Host "Previous contract line count: $($Prev.Count)" @Color2

    Write-Host "Current contract line count: $($Curr.Count)" @Color2

    Write-Host "-------------------------------------------------------"

 

    # Find out what the maximum line count is between the two contracts.

    $Y = $Prev.count, $Curr.count | Measure-Object -Maximum |

         Select-Object -ExpandProperty Maximum

 

    # Loop through the contracts line by line.

    # The IF Statements makes sure that if one contract is longer then

    # the other, that the extended text will be marked red.

    For ($X = 0; $X -lt $Y; $X++)

    {

 

        Try

        {

            If ($Curr.count -ge $Prev.count)

            {

                Write-Host "[$($X)]" -NoNewLine @Color3

                $P = $Prev[$X].ToCharArray()

                $C = $Curr[$X].ToCharArray()

                Write-Line -LongLine $C -ShortLine $P

            }

        }

        Catch

        {

            Write-Host $Curr[$X] @Color1

        }

           

        Try

        {   

            If ($Curr.count -lt $Prev.count)

            {

                Write-Host "[$($X)]" -NoNewLine @Color3

                $P = $Prev[$X].ToCharArray()

                $C = $Curr[$X].ToCharArray()

                Write-Line -LongLine $P -ShortLine $C

            }

        }

        Catch

        {

            Write-Host $Prev[$X] @Color1

        }

 

 

    } # End: For ($X = 0; $X -lt $Y; $X++)

<#

.SYNOPSIS

Compares two sets of texts for differences.

 

.DESCRIPTION

Compares two sets of texts for differences.  Highlights lines with

different characters in red.

 

.PARAMETER Previous

The text file of the previous contract.

 

.PARAMETER Current

The text file of the current contract.

 

.EXAMPLE

Compare-Contract -Previous Previous.txt -Current Current.txt

 

.NOTE

Output is written to the host utilizing Write-Host.  Output to an object

is not part of this codes design.

 

#>

} # End: Compare-Contract