Monday, September 19, 2016

Making array lookups faster



powershellThis post is about making lookups in arrays as fast as possible. The array can have may properties or few, it really does not matter. The only thing required is something unique that identifies each row of data.
So from time to time I find the need to make lookups fast. Usually it is a result of importing a huge csv file or something.



Sample data

First we have to create some dummy sample data which we can run some tests against. We will create an array of 10001 objects with a few properties. The unique property that identifies each row is called ID:


(sample data script)



How to test performance?


There are a couple of items that impact performance in Powershell. For instance running a Measure-Command expression will yield quite different results. Normally the first run is slower than the second one and then the standard deviation is quite large for consequent runs. To decreate the standard deviation, I use a static call to the .net GarbageCollector with [gc]::Collect(). I feel that the results are more comparable with this approach.



First contender Where-Object

There are two ways you can query an array with the Where keyword. You can pipe the array to the Where-Object cmdlet or you can use the Where method on the array. The where method will always be faster that the cmdlet/pipline approach since you save moving the objects through the pipeline. For our test, we will therefor use the where method as the base which we measure the performance against.
We are going to run 11 different queries and find 2 unique elements in the array. The time measured will be ticks. I have created an collections of IDs which we will use when we query the data ($CollectionOfIDs):


(Measure the Where method)

image

That is about 85ms on average to query the collection for two unique IDs. Base line ready.



There is a fast knock at the door

We have a new contender and he calls himself Hashtable. He claims he can do even better that 85ms on average. Challenge accepted.
First we need to create a hashtable representation of the $csvObjects collection/array. That should be pretty straight forward. We let the unique identifier (ID) become the key and the object itself the value:

(hashtable of csv)

Now I know you have a question. What is the performance penalty of converting that array to a hashtable? Good question and I am happy you asked. It converts the 10000 objects into an hashtable in apx 53 milliseconds:

image

I would say that is a small price to pay.
Using the same ($CollectionOfIDs) as we did for the where method, let’s run the same test against the hashtable:

(Measure the hashtable)

image

Okay, so the first one is quite slow about 11ms, however it improves quite dramatically to 0.038ms. I we use the average numbers (in ticks) to be fair, we have increased the performance with a factor of 649 (837265 / 1289).



Implications

I have only tested this on WMF 5.1 (5.1.14393.103). To use the Where query method on arrays, you need version 4 or later. Converting the collection to an hashtable will give you the ability to perform super fast queries. If you are querying a collection frequently, it makes sense to use hashtable.


Code for speed if you need it, otherwise write beautiful code!

Cheers

Tore

Thursday, August 18, 2016

Creating Menus in Powershell





I have created another Powershell module. This time it is about Console Menus you can use to ease the usage for members of your oranization. It is available on GitHub and published to the PowershellGallery. It is called cliMenu.






Puppies


This is a Controller module. It uses Write-Host to create a Menu in the console. Some of you may recall that using Write-Host is bad practice. Controller scripts and modules are the exception to this rule. In addition with WMF5 Write-Host writes to the Information stream in Powershell, so it really does not matter anymore.



Design goal


I have seen to many crappy menus that is a mixture of controller script and business logic. It is in essence a wild west out there, hence my ultimate goal is to create something that makes it as easy as possible to create a menu and change the way it looks.
  1. Make it easy to build Menus and change them
  2. Make it as "declarative" as possible

Menus


The module supports multiple Menus, however only one Main-Menu with as many Sub-Menus as you like. Each menu has a collection of Menu-Items that the user can choose from.

Example menu:

image


Menu options


Currently you can control the following aspects of the menu (they are shared across all menus unless you change them before showing a sub-menu):

  • Choose the char that creates the outer frame of the menu
  • Change the color of the frame
  • Change the color and DisplayName for the Menus
  • Change the color and Heading for the Menus
  • Change the color and Sub-Heading for the Menus
  • Change the color and DisplayName for the Menu-Items
  • Change the color and footer text for the menus
  • Change the Width of the Menu

Menu-Items


Menu-Items are the elements your users can invoke in your Menu. They have a ScriptBlock and a DisableConfirm switch parameter in addition to a Name and DisplayName. With the DisableConfirm parameter, you may selectively force the user to confirm the action before it is invoked.  



Validation and Return value


The goal of this module is neither. As a tool-builder you are responsible for validating user input when they invoke the ScriptBlock associated with the Menu-Item. 

Any output from the ScriptBlock will be written in the console. As you may know, a ScriptBlock may be a small script or a call to a cmdlet with parameters. I would suggest that you stick to calling custom or built-in cmdlets and design it using the best practice guides from Microsoft in regards to mandatory parameters etc.



Show-Menu


This is the core cmdlet responsible for building the Menu and displaying it to the user. Executed without parameters it will display the Main-Menu (remember you can only have one Main-Menu). Nevertheless you may also use it to display Sub-Menus by specifying the parameter MenuId which is the index of the menu. 

Further you may also invoke a specific Menu-Item in a specific Menu by supplying InvokeItem and MenuId parameters. If the Menu-Item is defined to confirm with the user before invocation, it will prompt the user with a confirmation request before execution. You can override this with the -Force parameter to execute it directly.



Examples


A menu which uses the Show-Command cmdlet (complete script in example.ps1):

image

An example with a Main-Menu and Sub-Menu:

image

image


Big thank you to Fausto Nascimento for invaluable input and suggestions!


That is it. If you have any questions or issues, look me up on twitter (@toreGroneng) or file an issue on GitHub.

Cheers

Tore




Sunday, May 8, 2016

Identity Manager and Powershell


image
It is year 2016 and Identity Manager looks like it did in 2010 when Forefront Identity Manager (FIM) was released. Who came up with the name and added it to the Forefront portfolio anyway, crazy stuff. As you probably know, looks can be deceiving. Even if MIM looks the same and run basically the same features, it is still a powerful state machine. I have been buzy collecting scripts and tools I have used the last couple of years and have started on 2 Powershell modules for MIM. This post is just a brief introduction to the module and the plans for the future.


Why create a module

Wait a minute. Does not Identity Manager come with a Powershell module? No, it comes with a Powershell snap-in from 2010. Back in those days Snap-ins where the cool kids on the block and everybody created snap-ins for things that should be created as a module. I blame Powershell version 1.0, however they fixed that in Powershell version 2.0, I think. I use the snap-in as a nested module and have created a Powershell manifest for the snap-in. That way you can choose to load the snap-in as a module if you like (look in the FIMmodule folder for the manifest).

The Snap-In that comes with Identity Manager is very generic/crude and allows you to do almost anything you can in the Identity Manager portal. You just need to remember the syntax and the XPath queries that you need to run. Doable, nevertheless quite hard to remember and prone to producing errors. Hence the effort on my side to create a module that is easy to use and a lovely experience.

I also have a side project where I focus on Operation Validation in FIM/MIM using Pester. Pester is the Unit Test framework for Powershell and the Operation Validation framework from Microsoft. You can have a look at the unit test in this link “Operation Validation”. Point of this being an test you can run to validate you Identity Manager infrastructure and make sure that all the bells and whistles are working as they should. A nice way to detect if your infrastructure peers have installed a new domain controller you should install PCNS on!


Introducing the Identity Manager Powershell module

It is still work in progress and I am focusing in on the Get-CMDlets for all the different object types in FIM/MIM. Currently I have added the following cmdlets:


Name Description
Get-IMObject A generic cmdlet used by all of the Get-Cmdlets. It is responsible for running the core cmdlets in the Identity Manager snap-in
Get-IMObjectMember Used to list members of a group/set. It can list ComputedMembers or ExplicitMembers
Get-IMPerson Get person information
Get-IMPersonMembership Show person membership in Groups/sets
Get-IMSecurityGroup Show information about Security groups in Identity Manager
Get-IMSet Show information about Sets in Identity Manager
Get-IMSetUsage Show all related usage of a Set in Identity Manager
Get-IMXPathQuery Create simple XPath queries with hashtable
Out-IMAttribute Cast a ResourceManagementObject to a PSCustomObject Used by the Get-IMObject cmdlet


It is currently not on the PowershellGallery, however it will be in May 2016. The module will require Powershell version 4.0 (Windows Management Framework 4) or later. It may work with Powershell version 3.0, however I have not tested it with that version. It will work with either Forefront Identity Manager 2010 R2 or Microsoft Identity Manger 2016.

If you want to browse the code and have a look, you can visit the GitHub repro on this link.

Introducing the Identity Manager Synchronization Powershell module

But, wait, there is more :-) This month I will also publish a new Powershell module for the Synchronization engine in Identity Manager. Normally this would be executed as a VBscript per Microsoft. Nothing wrong with that and it works. I on the other hand would like to use Powershell to do this. Thankfully Microsoft has included a WMI/CIM namespace/class for Identity Manager that we can leverage to do this. My Identity Manager Synchronization module (IdentityManagerSynch) will support the following cmdlets:



Name Description
Get-IMManagementAgent List Management Agents or Agent details
Get-IMAgentRunProfile List the RunProfiles associated with an Agent
Get-IMAgentStatus List the last known status of an Agent
Invoke-IMAgentRunProfile Execute a RunProfile for an Agent
Invoke-IMManagementAgentMethod Invoke a CIM-method on the Agent


The cmdlets implement dynamic parameters for the agent and runprofile thus preventing you to try and start a runprofile that is not implemented in the agent. 

I may or may not include a cmdlet that enables you to search for Metaverse Objects. The synchronization client has a nice GUI that solves most issues and lets you poke around. From time to time I find myself wishing for a way to extract information from Metaverse that is not possible in the GUI.

Cheers

Tore

Sunday, April 24, 2016

Pester Operational Tests


image

I have created yet another GitHub repro "PesterOperationTest". Feels like I do this every week, however that is not the case.

But why?

The purpose of this repository is to collect Pester Unit tests for your infrastructure. Anything that is mission critical for you business deserves a tests that validates the correct configuration. It will make you sleep like a baby and stop worrying when you implement a change in your environment if you tests pass.

This will only become as good as the contribution you make to the repository. I would love to do all the work myself, however there is not enough time in the world. Think of it like you are helping yourself and at the same time a lot of other people could benefit from the test you create.

How?

My original thought was to organize this in folders, one for each vendor and with subfolders for each products and/or feature. The scripts will be published to the Powershell Gallery for easy and convenient access for everyone. The tests should not be specific to your environment, however as generic as possible.

My first contribution

Been working for some time now with Forefront Identity Manager. The last 6 months has changed a lot in terms of how I work and what tools I use. Pester – a unit test framework included in Windows 10 (and in Windows Server 2016) – has become one of my key assets. Heck it has made me better at my work and increased the value added for my customers. Thank you Pester!

I have published a first version of the Microsoft Identity Manager Test to the repro. It validates important stuff like


  • files/folders that need to be present
  • services that should be running and configured the proper way
  • scheduled task that should/could be enabled and configured

I will be adding more stuff later. Pull requests are welcome!

Cheers

Tore

Sunday, January 10, 2016

Desired State Configuration - Consistency


Happy new year! 

Ages since I blogged about DSC and found a little topic that might be something others also are wondering about.

I reached out to Chris Hunt (@LogicalDiagram) on twitter. If I understand him correctly, he was wondering about capturing the verbose stream during a system invoked (Consistency Scheduled task) check. DSC has a scheduled task called Consistency (full Task Schedule path is \Microsoft\Windows\Desired State Configuration) which launch every 30 minutes. This task does the equivalent of running the Start-DSCconfiguration cmdlet and making sure that the configuration does not drift from the desired state. Did this a long time ago, however I had forgotten how I could do it.



The scheduled task




image


As you already probably guessed, this is just a task that executes an powershell command using the cmdet Invoke-CIMmethod with some parameters: The task starts an hidden powershell window and executes the following command:


image

I have copied the command and applied it to a splatting variable. That makes it much easier to read:


(GIST - Consistency.ps1)

My original thought was to use the Write-Verbose “override” by defining a function called Write-Verbose and capture the verbose output from that. That is possible because Powershell has an internal command resolver that tries to find the command from this priority list (see help about_Command_Precedence):
  1. Alias
  2. Function
  3. Cmdlet
  4. Native Windows Command

If you create a function with the identical name of an Cmdlet, your function will be executed instead of the real cmdlet. This is also how proxy functions work.
Sadly I must say (no I am kidding), the developers of the Invoke-CIMMethod used fully qualified paths in their call to Write-Verbose so that was a no go.


Redirect streams


June Blender (@juneb_get_help) has written a nice article about redirecting streams on the ScriptingGuys blog (Understanding Streams, Redirection, and Write-Host in PowerShell). Read up about it, it way come useful one day like this moment because we are going to redirect the verbose stream and send it to a file.



Changing the Consistency Scheduled task

We are going to change the action of the task. I prefer to have a powershell file that is launched by the task scheduler instead of a command parameter. Change the action to something like this (you may of course change the path and filename):


image


The powershell file should have something like this:


(GIST - ConsistencyFULL.ps1)

I have added a $outputFile variable that is where the verbose stream will be written. In the foreach loop I write to the file each time a new item is added to the verbosestream/output. This way you can follow along with the DSC engine as is progress. As an alternative, you could just drop the pipe to the foreach loop and assign the output from the Invoke-CIMMethod and write that to the outputfile.

So how to you follow along with the verbose stream. You use the Get-Content Cmdlet with the wait parameter, like so:

Get-Content –Path "c:\temp\ConsistencyverboseStream.txt" -Wait

Of course the file has to exists before you run the Get-Content command. The Out-File cmdlet in the Consistency.ps1 script will create the ConsistencyverboseStream.txt file if it does not exists, however you may create it first and run the Get-Content with the wait flag to prepare yourself before you launch the Consistency Scheduled task.


That is all folks, cheers

Monday, October 26, 2015

Powershell Gallery – For your pleasure


Sad to say this, however I received an account for Powershell Gallery to be able to submit modules to the new PowershellGet (formerly know as OneGet)  ecosystem a looong time ago. Today was the first time I published a module to the repository. The work involved was, like I expected, very light. Process went smoothly and my module was uploaded within 10 seconds.

If you have not looked into it yet, I highly recommend you start to dig in. The statistics on www.powershellgallery.com show that there is a dramatic increase in downloads the last couple of months. I expect this to increate as time goes by and by the fact that there is a package management preview available for people with Powershell version 3.0 or 4.0 running in Windows Server 2008 R2, Windows7, Windows8, Windows Server 2012 and 2012 R2 (download link). Please note that the preview is dependent on .Net version 4.5.


First module

So what did I upload as my first module? Well after being on Windows 10 for a couple of months (yes, I did not install it at once it was available), I got tired of changing the PowerPlan my laptop was on using the GUI. I have a rather large Lenovo laptop with 2 batteries which people make a point of noticing.

Hence I created a small module that has two simple advanced functions:

  • Get-PowerPlan
  • Set-PowerPlan

You might have guessed the name of the module: PowerPlan. Code is up on GitHub and as I have mentioned, the module is published to PowershellGallery. Just search for PowerPlan or go to a powershell window (launched as administrator) and type one of the following:

image

The functions use Get-CimInstance for the Win32_PowerPlan class and the Activate method with Invoke-CimMethod cmdlet.

Please report any issues on GitHub or if you have any enhancements you would like to include. Pull-requests are welcome!

Cheers

Tore

Wednesday, October 14, 2015

Use powershell to validate Email address


A time comes along when you need to validate an Email address using Powershell. Created a function just for this purpose as an introduction to how you may create advanced functions in powershell.



This function will “validate” an email address using the System.Net.Mail namespace and output an Boolean value indicating if an string is a valid address. It uses a structure and style that is my personal preference. Feel free to comment if you like.


Basic learning points


  • It is an advanced function
  • It supports the pipeline
  • It displays how to create an instance of a .Net class



Cheers

Tore