Advanced Windows PowerShell Scripting Video Training

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

Tuesday, June 24, 2014

Comparing Optimization of Filtering in PowerShell

This morning in my Hunt Valley, MD PowerShell class, I extended yesterdays lesson (see yesterday’s post) into filtering optimization.  In the PowerShell world, we have a saying: “Filter to the Left”.  That means that you filter out as many objects as possible as close to the beginning of the piped commands as possible.  What we did was use the Get-EventLog cmdlet and filtered it in two ways.  We wanted to filter for Event ID 12.  In the Get-EventLog cmdlet, we used the InstanceID parameter with a value of 12.  In the second execution of Get-EventLog, we piped everything to Where-Object and filtered on the property InstanceID for a value of 12.  We then executed our code from yesterday to test the runtime for each one.

# Optimizing for Performance.

# Get-Help Get-EventLog -Parameter Newest

 

# Execute each section individually by highlighting

# the code and pressing F8.

Clear-History

 

# This is optimized

Get-EventLog -LogName System -InstanceId 12

 

# This is not Optimized

Get-EventLog -LogName System |

Where-Object InstanceID -eq 12

 

 

# Get the history information and execution times.

Get-History |

    Select-Object -Property CommandLine,

    @{N="ExecutionTime";

        E={($_.EndExecutionTime - $_.StartExecutionTime).TotalSeconds}} |

    Select-Object -Last 2

Here is the output from the fourth section.

CommandLine                                                                  ExecutionTime

-----------                                                                  -------------

Get-EventLog -LogName System -InstanceId 12                                      8.9346474

Get-EventLog -LogName System |...                                               14.6560631

You can see that the first command using its built in filtering capabilities is much faster than piping all the objects to Where-Object.

Monday, June 23, 2014

Using Calculated Properties to get Command Execution Time

We are finishing up day 1 here in my PowerShell class in Hunt Valley, MD.  Just finished up calculated properties and had a request to expand the demonstration that I used a bit.  We were using the Get-History cmdlet to explore calculated properties.  Here is the code and output that we had:

Get-History |

    Select-Object -Property CommandLine,

    @{N="ExecutionTime";

        E={$_.EndExecutionTime - $_.StartExecutionTime}} |

    Sort-Object -Property ExecutionTime -Descending |

    Select-Object -First 5

CommandLine                              ExecutionTime                          

-----------                              -------------                          

Show-Command                             00:01:48.0548277                       

Update-Help                              00:00:27.2509743                       

Get-Process | Select-Object -Property... 00:00:07.7695634                       

Get-Service -Name BITS | Stop-Service... 00:00:05.8634245                       

get-eventlog                             00:00:05.4523953            

 

The question came up if there is an easier way to display the ExecutionTime property.  Our first step was to pipe this information to Get-Member to see the object type.

Get-History |

    Select-Object -Property CommandLine,

    @{N="ExecutionTime";

        E={$_.EndExecutionTime - $_.StartExecutionTime}} |

    Sort-Object -Property ExecutionTime -Descending |

    Select-Object -First 5 |

    Get-Member

    TypeName: Selected.System.Management.Automation.PSCustomObject

 

Name          MemberType   Definition                                   

----          ----------   ----------                                   

Equals        Method       bool Equals(System.Object obj)               

GetHashCode   Method       int GetHashCode()                            

GetType       Method       type GetType()                               

ToString      Method       string ToString()                            

CommandLine   NoteProperty System.String CommandLine=Show-Command       

ExecutionTime NoteProperty System.TimeSpan ExecutionTime=00:01:48.0548277

 

I highlighted in red the object type.  Our next step was to extract the value of this property and send it to Get-Member to see what properties we had to work in the object type System.TimeSpan. As an alternate to this next step, just go to MSDN and look up the .NET object System.TimeSpan.  

Get-History |

    Select-Object -Property CommandLine,

    @{N="ExecutionTime";

        E={$_.EndExecutionTime - $_.StartExecutionTime}} |

    Sort-Object -Property ExecutionTime -Descending |

    Select-Object -ExpandProperty ExecutionTime |

    Get-Member

    TypeName: System.TimeSpan

 

Name              MemberType Definition                                         

----              ---------- ----------                                         

Add               Method     timespan Add(timespan ts)                          

CompareTo         Method     int CompareTo(System.Object value), int CompareTo...

Duration          Method     timespan Duration()                                

Equals            Method     bool Equals(System.Object value), bool Equals(tim...

GetHashCode       Method     int GetHashCode()                                  

GetType           Method     type GetType()                                     

Negate            Method     timespan Negate()                                  

Subtract          Method     timespan Subtract(timespan ts)                     

ToString          Method     string ToString(), string ToString(string format)...

Days              Property   int Days {get;}                                    

Hours             Property   int Hours {get;}                                   

Milliseconds      Property   int Milliseconds {get;}                            

Minutes           Property   int Minutes {get;}                                 

Seconds           Property   int Seconds {get;}                                 

Ticks             Property   long Ticks {get;}                                  

TotalDays         Property   double TotalDays {get;}                            

TotalHours        Property   double TotalHours {get;}                           

TotalMilliseconds Property   double TotalMilliseconds {get;}                    

TotalMinutes      Property   double TotalMinutes {get;}                         

TotalSeconds      Property   double TotalSeconds {get;}    

 

We decided that the property TotalSeconds would be the best one to use in our scenario. In the Expression of the calculated property in line 4, we encapsulate our original expression inside of parenthesis. This allowed us to dot out the property of TotalSeconds from the object with minimal adjustment to our code.

Get-History |

    Select-Object -Property CommandLine,

    @{N="ExecutionTime";

        E={($_.EndExecutionTime - $_.StartExecutionTime).TotalSeconds}} |

    Sort-Object -Property ExecutionTime -Descending |

    Select-Object -First 5

CommandLine                                                         ExecutionTime

-----------                                                         -------------

Show-Command                                                          108.0548277

Update-Help                                                            27.2509743

Get-Process | Select-Object -Property...                                7.7695634

Get-Service -Name BITS | Stop-Service...                                5.8634245

get-eventlog                                                            5.4523953

 

And there you have it.  If you have several ideas on how to accomplish a task, you can use this method to determine which one is most efficient.  You may need to utilized TotalMilliseconds in a test environment for greater precision.  If your task includes reaching out to clients on the network, the network traffic and client availability will have an effect on the times reported.  It is best to test on a local system to determine the most efficient command.

Friday, June 20, 2014

How to get PowerShell to Greet You

This will go down as one of my more devious posts.

This week my PowerShell class seemed to be having from with my Out-Voice code that I published last year. One of them asked me if PowerShell could say good morning, afternoon, evening to you.  Well, Of course it can.  Since we were about to learn about IF statements, I turned this into an exercise. 

To get this to work, you need to accomplish 3 tasks. First, you need to create the script. Second, you need to set up a GPO to launch the script.  Third, set up a GPO to disable the 5 minutes delay in launching user logon scripts in Windows 8.1. 

Step 1: Set up the script.

You need to make my Out-Voice code available to PowerShell by downloading the code and placing it at the beginning of the logon script.  This will make it available to the local system. In the same script, copy the code below after the Out-Voice code.  Take a moment to look at the help file for Out-Voice.  You can set a female voice if you prefer.

1

2

3

4

$Hour = (Get-Date).Hour

If ($Hour -lt 12) {"Good Morning $($Env:UserName)" | Out-Voice}

ElseIf ($Hour -gt 16) {"Good Eventing $($Env:UserName)" | Out-Voice}

Else {"Good Afternoon $($Env:UserName)" | Out-Voice}

 

Line 1 gets the current hour of the day.

Line 2 will greet the user with “Good Morning” if it is before 12 noon

Line 3 will greet the user with “Good Evening” if it is 5 PM or later

Line 4 will greet with “Good Afternoon: if ether of the other two conditions fail.

Save this script to \\YourDomain.com\SYSVOL\YourDomain.com\Scripts\Greeting.ps1  The YourDomain.com is what ever your domain name is.

 

Step 2: Creating the GPO for the login script.

In this example, we are assuming that the user account(s) that you are scoping this GPO to is stored in an Organization Unit at the root of your domain called UserObjects. 

In the Group Policy Management Console right click UserObjects OU and click Create a GPO in the Domain, and Link it here…

Give the GPO a name and click OK.

Right click the GPO that you just created and click Edit.

Navigate to User Configuration\Policies\Windows Settings\Scripts (Logon/Logoff)

Double click Logon

Click the PowerShell Scripts tab.

Click Add.

Click Browse

Browse to the location in SYSVOL that you stored your script.  Select the script and click Open.

Click OK

In the drop down box for For this GPO, run scripts in the following order and select Run Windows PowerShell scripts first.

Click OK

Exit out of Group Policy Management Editor

 

Step 3: Created the GPO to allow login scripts to execute right away. (This step is only required for Windows 8.1 clients)

In this example, we are assuming that the computer account(s) that you are scoping this GPO to is stored in an Organization Unit at the root of your domain called Clients. 

In the Group Policy Management Console right click UserObjects OU and click Create a GPO in the Domain, and Link it here…

Give the GPO a name and click OK.

Right click the GPO that you just created and click Edit.

Navigate to Computer Configuration\Policies\Administrative Templates\System\Group Policy.

Open the settings for Configure Logon Script Delay

Select Enabled

Set the number of minutes to 0.

Click OK.

Exit out of Group Policy Management Editor

 

Now wait.  Normal Active Directory replication must occur, the clients must refresh their GPOs, and the users must login.  If your clients or users do not receive the GPOs, perform your standard troubleshooting methodology for Group Policy.

Thursday, June 19, 2014

How to filter out objects from Get-Volume that do not have a drive letter

While delivering a PowerShell class this week, I utilized the Get-Volume cmdlet to help me demonstrate filtering with Where-Object.  I came across a small problem.  Take a look at this output.

PS C:\> Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype

 

               DriveLetter FileSystem                 DriveType               

               ----------- ----------                 ---------               

                         D NTFS                       Fixed                   

                         C NTFS                       Fixed                   

                         E NTFS                       Fixed                   

                           NTFS                       Fixed                   

                           NTFS                       Fixed                   

                           NTFS                       Fixed  

 

I attempted to filter out all DriveTypes that did not have a drive letter.

The following did not filter at all.

Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype |

Where-Object {$_.DriveLetter -ne $Null}

 

Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype |

Where-Object {$_.DriveLetter -ne ""}

 

Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype |

Where-Object {$_.DriveLetter -ne " "}

 

Somewhere, there was a hidden character.  I first focused to the DriveLetter property on one of the objects that did not have a DriveLetter.

$D = Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype

$D[4].DriveLetter

 

Next I decided to discover the ASCII code for this hidden character

[int][char]$D[4].DriveLetter

 

It was zero

Filtering for zero did not work.

Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype |

Where-Object {$_.DriveLetter -ne 0} 

 

One of my students suggested looking at the escape characters.  Sure enough, `0 means NULL.  Take a look at this excerpt from About_Escape_Characters

The following special characters are recognized by Windows PowerShell:

 

        `0    Null

        `a    Alert

        `b    Backspace

        `f    Form feed

        `n    New line

        `r    Carriage return

        `t    Horizontal tab

        `v    Vertical tab

 

Now this works:

Get-Volume | Select -Property DriveLetter, FileSystem, Drivetype |

Where-Object {$_.DriveLetter -ne "`0"}