Advanced Windows PowerShell Scripting Video Training

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

Wednesday, January 4, 2017

Using functions with PowerShell Background Jobs Part 2 of 2

Yesterday we learned how to use the InitializationScript parameter of Start-Job. Today we are going to allow for further modularization of our code and send multiple functions to Start-Job.  We could very easily send multiple functions in the same script block, but I need to pick and choose which functions I will be working with for each process so I need to be able to send them separately.  Here is our code.




$JobFunction1 = {
 Function Beep
 {
    Param ($Tone)
    [console]::beep($Tone,200)
 }

}

$JobFunction2 = {
 Function Beep2
 {
    Param ($Tone, $Time)
    [console]::beep($Tone,$Time)
 }
}

$InitializationScript = $executioncontext.invokecommand.NewScriptBlock("$JobFunction1 $JobFunction2")

$JobSplat = @{
    Name = "Test1"
    InitializationScript = $InitializationScript
    ArgumentList = 300, 400, 200
}

Start-Job @JobSplat -ScriptBlock {
            Param($Value, $Tone, $Time)
            Beep -Tone $Value
            Beep2 -Tone $Tone -Time $Time
            }

A lot of the code is the same as yesterday with a few exceptions. Notice that we are creating $JobFunction1 and $JobFunction2.  This allows me to place a single function inside of a script block, but be able to send multiple script blocks to Start-Job.  I am also using the $ExecutionContext automatic variable. According to About_Automatic_Variables, this variable:
Contains an EngineIntrinsics object that represents the execution context of the Windows PowerShell host. You can use this variable to find the execution objects that are available to cmdlets.

OK, that was informative.  It is on object of type System.Management.Automation.EngineIntrinsics. In short, you can create new script blocks with it.  I use it to join the 2 variables containing the script blocks that I need to send to Start-Job. I save the output in a variable called $InitializationScript. This is now the value of –InitializationScript.


When you run this code, you will hear two beeps.

Tuesday, January 3, 2017

Using functions with PowerShell Background Jobs Part 1 of 2

Happy New Year everyone!  I am spending my New Years’ day working on some code that I’ve been putting off while the family has been in town.  Something about shoveling sunshine as opposed to shoveling snow.  I’m working on expanding some Azure code that I have developed and I’m looking at ways to further modularize the code.  Since I use Background jobs with script blocks to speed the processes that I am running, I’m looking at using the InitializationScript parameter of Start-Job.

The InitializationScript parameter allows you to run code before the ScriptBlock parameter runs.  When you include functions inside of it, you are able to place those functions in the same memory that the ScriptBlock will execute in.  Let’s take a look at our code to set this up.

First we create a variable that will hold our function that we will call from the background job.

$JobFunctions = {
 Function Beep
 {
    Param ($Tone)
    [console]::beep($Tone,200)
 }

}

In this case, we are going to make the console beep.  We are also going to pass the value for the tone of the beep to the parameter $Tone.

Next we will set up a splat for a few of the parameters of Start-Job. Notice that we are setting the value for –InitializationScript to be the $JobFunctions that we created above.  Also, we need to pass a value to what will be our script block.  That value is 300.

$JobSplat = @{
    Name = "Test1"
    InitializationScript = $JobFunctions
    ArgumentList = 300
}

Now we can run our background job.

Start-Job @JobSplat -ScriptBlock {
            Param($Value)
            Beep –Tone $Value
            }

First off we call our splat and then we call our script block.  We need to pass the value of 300 to the script block so we created a parameter called $Value. In other words $Value = 300.  Next we call the function that we sent to the initialization script.  The function name is Beep it has a parameter called –Tone.  We provide it the value of 300 that is contained in $Value.  Once this runs, you will hear a beep.


Tomorrow we will send multiple functions to our background job. 

Thursday, December 22, 2016

Using Here-Strings to help search United Airlines for Flight Dates

As many of you know, I am fortunate to teach Windows PowerShell, Server, and Client all over the world.  One thing that I do not do very often is use my air miles.  This is has been a very deliberate action because I wanted to make sure that when my wife decides to fly to Europe with me, she will do so in style. 

Well, the time has come.  I’m heading over to Europe to speak at the PowerShell Conference in a few months and my wife and I are going to spend some time together hunting down what we hope will be distant relatives and doing a little sightseeing.  So, I’m burning the air miles to fly family to my home to house sit and for us to fly over the pond in United Polaris Class.  My wife does not like long flights so I am determine to spend the air miles wisely to make sure she is as comfortable as possible.  I’ve made the flight many times in coach, but I would be a bad husband if I did not splurge a bit on my wife. Below is the difference.


Business/Polaris

What I usually fly…. Economy.


Our schedule is extremely flexible so I’m searching all of the airports in central Europe for days when United puts a premium cabin “on sale”, so to speak, for award mile use.  To help make this daily ritual less time consuming, and to give me a good lesson to share on Here-Strings with my class, I came up with the code below.

A few things first.  If you have a United Mileage Plus account, open your default web browser and log in.  Leave the browser open when you execute the code. Otherwise the queries will not be executed with your account.

You will also need to manually search for award travel to each destination.  You will need to replace my URL strings with yours for each search that you make.

Finally, you will need to replace the date component of the URL with $FlightDate.  Look for a date with a format of YYYY-MM-DD in the URL from United.  It is easy to find.

Once done, just save the code and press F5 to put it in memory. (You will need to change the default values of the parameters to meet your desired travel date. I marked the 3 places in the param block of the code.)

Type Search-United and press Enter.  All of your queries will run at the same time.  Remember to start this process 6 months in advance if possible.  This will help you find more award mile saving dates.

Function Search-United
{
[CmdletBinding()]
Param (
    [Int]
    $Month = <#Replace with your default Month#>,
   
    [Int]
    $Day = <#Replace with your default Day#>,
   
    [Int]
    $Year = <#Replace with your default Year#>
    )

#Create a DateTime object based on the flight date.
[DateTime]$Date = "$Month-$Day-$Year"

# Convert that DateTime object into the format the United website requires.
$FlightDate = $Date.GetDateTimeFormats().split("`n")[5]

# Here-String to list all destinations to check.
$SearchList = @"
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=MUC&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=FRA&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=NUE&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=SZG&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=VIE&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=PAR&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=GVA&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=ZRH&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=MIL&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=VCE&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
https://www.united.com/ual/en/us/flight-search/book-a-flight/results/awd?f=PHX&t=ROM&d=$FlightDate&tt=1&at=1&sc=7&px=2&taxng=1&idx=1
"@

# Open a web page for each destination.
$SearchList.Split("`n") | ForEach-Object {Start-Process -FilePath $_}

<#
.SYNOPSIS
Allows you to search multiple destinations at United Airlines.

.DESCRIPTION
Allows you to search multiple destinations at United Airlines.

First you must open your default web browser and log into your United Mileage
Plus account.  Mileage Plus members receive better access to award miles
savings so you should see more options.

Setup:
You must manually search each destination and make sure to select
"Award Travel" on the website.

Copy the web address into the Here-String above. Replace the date in
the string with $FlightDate.  The string to replace will bi in the
format YYYY-MM-DD.

Run this code when you want to check for award travel.

.PARAMETER Month
The numeric value of the month to travel.

.PARAMETER Day
The numeric value of the day to travel.

.PARAMETER Year
The numeric value of the year to travel.

.Example
Search-United

Opens the United website and looks for award travel on the default dates.

.Example
Search-United -Month 6 -Day 15 -Year 2017

Opens the United website and looks for award travel June 15, 2017.

.NOTES
===============================================================================
== Cmdlet: Search-United                                                     ==
== Author: Jason A. Yoder                                                    ==
== Company: MCTExpert of Arizona                                             ==
== Date: December 21, 2017                                                   ==
== Copyright: All rights reserved.                                           ==
== Version: 1.0.0.0                                                          ==
== Legal: The user assumes all responsibility and liability for the usage of ==
== this PowerShell code.  MCTExpert of Arizona, Its officers, shareholders,  ==
== owners, and their relatives are not liable for any damages.  As with all  ==
== code, review it and understand it prior to usage.  It is recommended that ==
== this code be fully tested and validated in a test environment prior to    ==
== usage in a production environment.                                        ==
==                                                                           ==
== Does this code make changes: NO                                           ==
===============================================================================
#>

}


Tuesday, December 13, 2016

Exchange Online Error: You must provide a required property: Parameter name: UsageLocation

I’m continuing my efforts to update MOC 20697-2 this morning.  I’ve decided to add additional information on Office365.  Microsoft removed over 2000 SaaS products from Azure in October of 2016.  This resulted in 2 lessons of this class now being void.  While adding in content for Exchange Online, I discovered an error.

Set-MsolUserLicense : You must provide a required property: Parameter name: UsageLocation
At line:1 char:1
+ Set-MsolUserLicense -UserPrincipalName "KFrog@Adatum2008JY.onmicrosof ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Set-MsolUserLicense], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.RequiredPropertyNotSetException,Microsoft.Online.Administration.Automation.SetUserLicense

This error played with me for a while.  It is telling me that I am missing a property and its’ parameter name is UsageLocation.  I went to the help file for Set-MsolUserLocation, but that parameter is not part of the cmdlet.  What I discovered is that the user’s Azure AD object has a property called UsageLocation and that it was NULL.  I utilized the Set-MsolUser cmdlet with its –UsageLocation parameter and set the value to “US”.

Now this works:

$License = (Get-MsolAccountSku | Where AccountSkuId -like "*ENTERPR*").AccountSkuId

Set-MsolUserLicense -UserPrincipalName "KFrog@Adatum2008JY.onmicrosoft.com" -AddLicenses $License


Monday, December 12, 2016

Removing and Unwanted PowerShell Module

This evening I’m enjoying my warm hotel room. I’m in Saskatoon, Canada in winter teaching PowerShell so no sight seeing this trip. On the plus side, I’m prepping to teach MOC 20697-2B next week from the comfort of my office in Phoneix.  Naturally, I’m looking over my PowerShell code for the class and making sure there have not been any surprise changes with Azure or my cmdlets from the PSGallery.

I’ve noticed that the module for OneDrive has a version change.  The problem  is, I already installed the new one.

PS C:\> Get-Module -Name OneDrive -ListAvailable


    Directory: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version    Name          ExportedCommands                                                   ---------- -------    ----          ----------------                                                               
Script     1.0.3      OneDrive      {Get-ODAuthentication, Get-ODWebContent, Get-ODDrives... 

Script     0.9.2      OneDrive      {Get-ODAuthentication, Get-ODWebContent, Get-ODDrives...


Fortunately, Uninstall-Module has a parameter called –RequiredVersion.  Just provide it with the version number of the module that you want to remove to prevent you from accidentally removing the newer version.

PS C:\> Uninstall-Module -Name OneDrive -RequiredVersion 0.9.2 -Verbose
VERBOSE: Performing the operation "Uninstall-Module" on target "Version '0.9.2' of module 'OneDrive'".
VERBOSE: Successfully uninstalled the module 'OneDrive' from module base 'C:\Program Files\WindowsPowerShell\Modules\OneDrive\0.9.2'.


Now only one version remains.

PS C:\> Get-Module -Name OneDrive -ListAvailable


    Directory: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version    Name                                ExportedCommands                                                               
---------- -------    ----                                ----------------                                                               
Script     1.0.3      OneDrive                            {Get-ODAuthentication, Get-ODWebContent, Get-ODDrives, Format-ODPathorIDStrin...


Friday, December 9, 2016

Auto Populating a Parameters’ Value from a Dynamic List

First off, I want to give a shout out to Author: Martin Schvartzman and his blog posting https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/.

A question that I often get when teaching parameter validation is "can you load the values of a parameter dynamically?" Up until now, my answer was no.  Time to change that.  After getting that question again, I did some more research and found Martin’s article.  Simply adjusting 1 line of the code from his blog posting allowed me to load the SamAccountNames of all users in the domain as the valid, and TAB complete capable, values of a parameter.  Below is that code:

# Author: Martin Schvartzman
# https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/
# Minor modifications: Jason Yoder

function Test-DynamicValidateSet {
    [CmdletBinding()]
    Param(
        # Any other parameters can go here
    )

    DynamicParam {
            # Set the dynamic parameters' name
            $ParameterName = 'User'
           
            # Create the dictionary
            $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

            # Create the collection of attributes
            $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
           
            # Create and set the parameters' attributes
            $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute.Mandatory = $true
            $ParameterAttribute.Position = 1

            # Add the attributes to the attributes collection
            $AttributeCollection.Add($ParameterAttribute)

            # Generate and set the ValidateSet.
            # Change the next line to produce what you want to auto populate for the parameter.
            # Make sure it is DataType String.
            $arrSet = Get-ADUser -Filter * | Select-Object -ExpandProperty SamAccountName
            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)

            # Add the ValidateSet to the attributes collection
            $AttributeCollection.Add($ValidateSetAttribute)

            # Create and return the dynamic parameter
            $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
            $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
            return $RuntimeParameterDictionary
    }

    begin {
        # Bind the parameter to a friendly variable
        $User = $PsBoundParameters[$ParameterName]
    }

    process {
        # Your code goes here
        Get-ADUser -Identity $USer
    }

}