PowerShell Icon

In this Post we will be looking at how to use methods in PowerShell. When thinking about methods parameters are bound to come up. In C# parameters do not get much glory. But in PowerShell parameters do come with some extra features. Which can be reused when invoking a script from the command line.

In the previous posts we saw how to get setup and in Part 2 how to the basic command structures can be implemented. In this post I’ll assume you are familiar with the topics of those posts. So if you are new to PowerShell you might want to read the posts to get familiar with some basic concepts.

Methods and Parameters

Though PowerShell does not require any methods from the get go. It does provide the structure to make code reusable by putting it into a function.

The C# function above could be translated to a PowerShell as follows.

Most functions take parameters, so let’s do that, again leading of with the C# function:

And the corresponding PowerShell code:

As you can see the PowerShell function uses a special keyword.  The parameter name starts with a dollar sign. Type Information is also added to the parameter. It is optional to define the type and if not wanted can be simply left out. Invoking the function does not require any braces for the parameter and they will default to the order they are defined in the method. Now let's look at the following code:

Parameters in PowerShell provide some interesting ways. The previous samples shows how we can write a method with multiple parameters. And also how we can set a parameter by it's name. But we are only scratching the surface of what is possible. The common scenario to start a PowerShell script is from  the Command Line Interface (CLI). To keep a script flexible it makes sense to start it with parameters e.g. IP or URI of a server. When defining the same construct as in the method we can have a script requiring parameters.

The script can then be invoked further as follows:

Note that the name of the parameter is reused for the command line parameter. But we can do even more, lets consider the following method description:

We now have three parameters which are assigned default values similar to the way they are done in C#. We can further set the order of the parameters, make a parameter mandatory and even checking a parameter as follows.

Summing it you can see that PowerShell provides a  way to  work with methods and provides a rich way on interacting with  parameters. The parameters can also be used when writing a script. Simply place the parameter code at the top of the script and the parameters can be set when invoking the script.

File handling

No introduction on PowerShell would not be complete if we wouldn’t have a small section regarding file handling. Writing to a File is as easy as writing the following line:

This way we can easily persist information for later usage or inspection of a state during runtime. If the goal is to persist the state of a PowerShell object model. Serialization will serve as a better alternative. Serializing an object provides the option of restoring it’s state at a later time. Allowing to inspect the object in the REPL of PowerShell and analyze why a certain condition may have lead to a failure. Serializing an object in PowerShell can be realized with the following command:

Deserializing an object will be performed with the following line:

Storing state by serializing objects into an XML file can provide as an elegant solution for transferring state between machines or rolling back to a previous state if an error occurs during the execution of a script. One could also use the serialized objects for automated tests without having to touch the actual system. Let this be my next blog post relating to PowerShell.


In this post we saw how basic control structures can be created with PowerShell such as:

  • Methods and Parameters
  • File handling
  • Serializing and deserializing objects

With these basic control structures you are able to create simple scripts and reuse code by defining methods. As PowerShell scripts start to grow, testing them gets more and more difficult. This is why in the next post we will be looking into automated testing with PowerShell.


In the first part of the series we covered the development environment setup on how to get started with PowerShell. Now lets dive into some code. PowerShell can be used as a dynamic language. For a C# developer this can be one of the most frustrating points. In this post we will look at the following points:

  • Variables
  • If/else
  • Loops and Piping
  • Methods
  • File handling

So let’s get going Smile


When we look at a simple program of C# it might look something like this.

using System;
namespace ConsoleApplication
public class Program
public static void Main(string[] args)
string name = "Harvey Specter";
int number = 42;
Console.WriteLine($"Hello{name}, your number is{number}");
view raw Program.cs hosted with ❤ by GitHub

Now in comparison here is the equivalent PowerShell code.

Note that we do not need any Class or Method to get started. Simply start writing your script. Now variables are interesting under PowerShell. Lets add some more info to our PowerShell code to retrieve the type of the variables. The variable is assigned a type when a value is assigned. Since PowerShell is not compiled there are some potential pot holes a typical C# developer might into. For starters this is a totally valid statement.

Resulting in the following output:

Variable is first of Type Int32 after assignment of a string has the type String.

We can be more strict in PowerShell by defining the type of the variable which will make the second assignment illegal. But this requires some additional effort on your end.

If we would run the strict assignment we would be greeted by an error message which is more of what a C# developer would be used to.

And one more thing. Even though the variable $neverDefined never got defined. Well we can still access it’s value without an exception or error being raised.

PowerShell output showing that the variable $neverDefined simply shows an empty string

Keep this in mind while developing since they might just come around and bight you in the foot later on.

Conditional Operators

When writing conditional code in C#, the standard choice is using if and else or for multiple options a switch/case. So a possible option would be to use them as follows:

Apologizing to all the readers who have to work shifts Winking smile Lets look at how the same code would be implement in PowerShell:

No huge changes or surprises So no surprises here. The major difference is the equality sign in the if check. Here is a small translation table of the equality signs you find in C# and PowerShell:







Not Equal



Greater Then



Less Then



Greater or Equal



Less or Eual



Loops and Piping

There are many different constructs for looping in C#: for, while, do while and ForEach. So if we look at all the different types of loops in C#:

In PowerShell the equivalent can be  implemented like so:

Now the ForEach loop is really great when having to iterate over a list of items. This is often what we end up doing e.g. “Iterating over a list of people to get the count by city” or a bit more PowerShelly “Iterate over number of host information to ensure that everything is okay and no action is needed”. While we could write that with the above for loop, there is a PowerShell called piping. Piping allows us to Take a collection and forward it to the next operation. We could rewrite the ForEach sample as follows:

Pretty cool no? Smile We can even use the ForEach construct to loop over every item being forwarded:

Note that $_ is always the current item we are going over in the ForEach Loop. The equal construct in C# is achieved with Extension Methods. Piping can be great to enhance readability since one can see the flow. But it also can make the code harder to debug, so be sure to keep the balance here.

Note: Even though foreach is an alias for ForEach-Object they behave differently. When using foreach the operation is paused until all elements are to be processed are present, in case of ForEach-Object it will process the items as they come in. This may lead to some unexpected side effects…


In this Blogpost we saw the basic programming structures in PowerShell compared to how they would be implemented in C#. Keep in mind that PowerShell is more dynamic and forgiving at runtime than C# which might lead to some unwanted side effects. In the next Post we will look at how we can implement Methods and work with Parameters which are not only handy for methods but also for Command Line Interface parameters.


There is more in this blog post series:


This has been driving me bonkers the last couple of days so I just wanted to jot down the steps to get the Emulator up and running under Windows 10. In my case after upgrading from Win 8.1. So if you ever received one of the following errors:

  • [Critical] An internal virtual network switch is required for emulated devices to run.
  • [Critical] XDE Exit Code: CouldntCreateInternalSwitch (16)
  • [Critical] XDE Exit Code: CouldntStartVm (10)
  • [Critical] XDE Exit Code: InvalidArguments (3)
  • For UDP connection errors see update of July 2016 at the end.

These steps should help you bring the Emulator back up and running:

Disclaimer: Please note that you perform these steps at your own risk. Generally speaking all should run just fine but some steps will remove some Hyper-V settings and this might affect your network connectivity or virtual machine setup. So take these steps as worked on my machine advice.

  1. Ensure no XDE.exe task is running (Task Manager)
  2. Repair Android SDK – Open Programs and Features > Microsoft Visual Studio Emulator for Android > select Change in the menu bar and choose Repair in the Visual Studio dialog
  3. Remove All Hyper-V virtual switches – open the  Hyper-V Manager > select the Virtual Switch Manager… (located in the menu on the right) > select each virtual switch and select remove > click onto Apply
    1. If there is an error while removing a virtual switch, try restarting your computer
  4. Run XdeCleanup.exe – Depends on your install but on the Surface Pro 3 you should find it under: "C:\Program Files (x86)\Microsoft XDE\10.0.10240.0"

Now try to get your Emulator up and running. If you still receive error messages try the following steps:

  • (Surface Pro 3) Reinstall the network drivers > Open the Device Manager> under View select Show hidden devices > Uninstall Marvell AVASTAR Wireless-AC Network Controller and Surface Ethernet Adapter > Restart which will automatically reinstall the drivers from the recovery partition
  • Clean up network bridges > Open Network Connections > Add Bridge (this option only showed up the first time) > Remove the added bridge again

Now your Emulator should fire up.


I had to repeat step 3 a couple of times – even after the emulator would start up the first time but maybe that is just a configuration issue on my machine…

Hope this helps and happy coding! Smile



Update - 20. July 2016

Managed to wreck my Android Emulator again yesterday. This time none of the above attempts fixed it for me. Since this is one of the more frequented blog posts I thought I would update to share another possible solution.

The Error message was that no UDP connection could be established with the Emulator. Following these steps solved the issue:

  • Open Device Manager (On Win10 simply search for Device Manager in the Start Menu)
  • Under Viewselect Show hidden devices
  • Delete all virtual network devices except your Network card (you do not have remove the Bluetooth devices)
  • Open Hyper-V and remove all Hyper-V virtual network endpoints as described under Point 3
  • Reboot
These steps solved the mentioned issue above and is based on the following Troubleshooting articleby Microsoft.



On the 6. October 2015 Microsoft introduced it’s new devices all destined to run Windows 10.

The first Device was the HoloLenswhich was demoed with a immersive game experience showing how HoloLens can integrate the furniture of your living room in the game. Plus the HoloLens should start to be available next year for developers for 3000$, so far only US availability has been announced, but my hopes are still high that it will reach Europe and other countries outside of the US soon after that.


After the HoloLens the new Microsoft Band 2 was introduced. The specs of the band leaked before the event and they seem to be have quite spot on. The new band has a curved display, looks sleeker and has an additional 11th sensor (a barometer) which allows it to track elevation/steps. The band is focused on sport and tracking the users physical activities. The data is stored in the Microsoft health service which allows the user to analyse all of his activities i.e. golf, sleep, running and many more. The Data is stored as usually done with these services in the cloud and not on the devices of the user.

Further Microsoft partnered up with quite a few companies to ensure the band will have apps that provide the user with additional apps and notifications right at your wrist.

Windows Mobile


With the Lumia 950 and 950 XL Microsoft finally has introduced two flagship phones which has been overdue and long awaited. Since the Lumia Icon/930 and Lumia 1520 which they are replacing have been on the market for years(!). The new Lumias keep true to their heritage of providing great Cameras (20MP incl. image stabilization), great displays and the obligate bump in battery size. Further the following specs stick out:

  • Expandable storage via SD-Card
  • 3 GB RAM
  • Snapdragon 808 processors
    • 6-Cores
    • 8-Cores XL
  • USB-C connector

The new USB-C connector allows an ease of use and greater bandwidth but there is more, with the new phones Microsoft introduces Continuum. With an additional accessory called a Microsoft Display Dock you can plug in your phone to a monitor, keyboard and mouse allowing you to control desktop applications such as Word, PowerPoint etc.. The apps that can be used will be based on the Universal Windows Platform (UWP) which allows developers to adopt for different screen sizes. So when the app provides resolutions for phone and desktop factors the same phone app will be displayed differently and allow the user to harness the full power of a desktop setup such as using a mouse and a real keyboard.

While connected to the Microsoft Display Dock the phone will still be available as a phone, meaning you can make calls, write and receive texts etc.. So it isn’t just simply projecting the screen of the phone to another display but it actually will bring up a (limited) Windows 10 desktop experience which I see some very interesting scenarios arising and allows you to use the phone as a PC! Smile

While the Lumia 950 und Lumia 950 XL are high end phones Microsoft also introduced the new Lumia 550 which will provide a cheaper alternative without the Continuum though but still providing quite some bang for the buck.

Surface Pro 4


The Surface Pro 4 is the expected update of the Surface Pro 3. While keeping the dimensions of the SP3 the SP4 comes with the latest Intel chipset, up to 16 GB RAM and 1 TB hard drive. These specs are a great bump and will allow to run Virtual Machines easily from your SP4. Keeping the dimensions will mean that all the external hardware accessories for the SP3 will work with a SP4 and vice versa. If you are the proud owner of a SP3 and have a dock. You will be able to simple reuse the dock for the SP4. All the hardware released for the SP4 also works for the SP3.

While keeping the overall dimensions the SP4 comes with a greater resolution which comes to the cost of the bezel. The screen now comes at 12.3 inches and sports 2736 x 1824 resolution which results in a really high res display at 267 pixels per inch (ppi).

Type cover

The new type cover comes with a full keyboard layout, 40% larger track pad and there will even be versions with a biometric finger reader. Real world testing will prove how much better it is overall but a full size keyboard layout surely sounds lovely.


The pen has been overhauled slightly. The backend tip now not only is the OneNote button but also serves again as rubber as it was the case with the SP1 & 2 pens. The pen tip can be interchanged which will allow artistic and design folks to choose individual brushes simply by changing the tip and sport the physical feel.


Another great plus is that the pen now attaches magnetically to the Surface, so no more after thought latches needed. I really like this additional feat as I never grew warm to the latch (in my case still in the original packaging…).

Docking Station


The new docking station no longer requires you to place the Surface Pro into it. It is an elegant little box that you can attach via the power connector. The new Docking Station provides gigabit Ethernet, two display ports, four USB 3.0 ports, audio out and of course power to the Surface Pro 4 and can be used with the Surface Pro 3.


(One more thing) Surface Book

The biggest surprise (very positive surprise) is the Surface Book. Other then the SP4 it comes with a Keyboard dock that can be removed at the push of a button. The design looks very sleek and though it does not close fully it resembles pretty much a laptop. In the keyboard half of the Surface Book are additional batteries and a custom made NVidia graphics card. So it has no problems stemming graphically intensive work such as 3D design or games.


Being able to remove the tablet results in a light weight and really thin tablet (the USB, Power and display ports are all in the keyboard part). The tablet has the form factor of an A4 paper so it should give you known dimensions and with a pen will allow you to get a great note, drawing, etc. paper.

All accessories from the SP4 are compatible with the Surface Book. But you will not be able to stick it into a SP3 docking station. But it will go nicely with the new SP4 docking station which is less bulky and just as clean.

The take away

Microsoft gave an awesome presentation and highlighted a lot of great features that they usually just seemed to forget to bring forward to the crowd. During the great presentation they highlighted the future with HoloLens, the next step for Windows Phone which will be renamed to Windows Mobile with Windows 10 and the great line up of Surface hardware.

With the new hardware I am sure the surface will continue to grow and expand in a market that is looking how to integrate tablets for the workforce which requires additional input compared to a candy crush app.

The phone hardware finally serves again the users that do want to spend some money for a device and brings some great power user features to the I-want-to-get-stuff-done minded people out there.

I personally can’t wait to get my hands on the new hardware and give it a run especially the phones continuum mode and the new Surface Book are looking very nice and I already fear the impact on my bank account Winking smile



In this blog post we will look at how we can merge multiple commits into a single one with the goal of reducing the chatter in a git log. This technique is generally known as squashing.

When to use it

When working on a new feature (User Story) it is best practice to often commit. This gives you the option of always reversing back to a safe spot without loosing a great amount of work. But once you commit the changes to a remote repository it would be nice to get the quintessence of your work within one/a few meaningful commit(s). Often all those small safety hooks no longer are helpful on the server repository and may even harm the flow of reading through the log and getting the big picture.

How is it done

You can either rebase based on the commit count you want to squash or the commit id:

git rebase -i 003ee6c6f34516ad325a72d430e5a269e470b4d3

Alternatively you can set the count of commits you want to rebase:

git rebase -i HEAD~4

Here we are telling git to rebase the last four commits. After executing the command your editor of choice for commit messages will popup:

pick 5629556 Adds second paragraph
pick 56ea060 Adds third paragraph
pick 892c090 Adds final paragraph

# Rebase 003ee6c..892c090 onto 003ee6c
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# These lines can be re-ordered; they are executed from top to bottom.
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
# Note that empty commits are commented out

Simply change the commands to squash i.e. s and your commits will be squashed into one single commit. Note you want to pick the starting point of your squashing:

pick 5629556 Adds second paragraph
squash 56ea060 Adds third paragraph
squash 892c090 Adds final paragraph

# Rebase 003ee6c..892c090 onto 003ee6c
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# These lines can be re-ordered; they are executed from top to bottom.
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
# Note that empty commits are commented out

Which merge your commit messages i.e. lets you edit the message that will be associated with the commit:

Some very meaningful merge commit message comes here.

# This is a combination of 3 commits.
# The first commit's message is:
Adds second paragraph

# This is the 2nd commit message:

Adds third paragraph

# This is the 3rd commit message:

Adds final paragraph

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# rebase in progress; onto 003ee6c
# You are currently editing a commit while rebasing branch 'master' on '003ee6c'.
# Changes to be committed:
#    modified:   someFile.txt

When to leave your fingers from this technique

Do not rebase commits that exist outside your repository.

With rebase you are changing the history of the git repository. If you do this on a history that you have published and that other people are using.. Let’s just say you will not be rewarded by many friendly words. As you will mangle the history which they are using to work upon leading into a big mess. So only apply rebasing to local repositories which you haven’t published yet. An exception is if you are the only committer to a repository (and do not have any other copies with work lying around..).


Using git rebase enables you to modify the commit history and make it more readable and less clunky. This helps you and your co-committers to have a nice log history with meaningful commits. Further it allows developers while coding to commit often to the local repository and easily go back in time if an approach has proven futile. All without littering the log history of the project and ending up with a ton of non-meaningful log entries.

Do however never rebase on public history as this might lead to tears and intense discussions.