Yesterday at AgileDotNet, before one of my sessions, we were discussing books which every software developer should read with the room, and particularly with a bunch of SMU students who came down to Houston to attend. I promised I would post the list of those books to my blog, so here they are:
DRY is an acronym that was created by Andrew Hunt and Dave Thomas in their book The Pragmatic Programmer. It stands for Don’t Repeat Yourself. We’ve espoused terse commands in all the previous chapters, but how to I avoid having to re-invent the wheel every time I open a PowerShell prompt.
Profiles
There is a script which runs every time you open a PowerShell prompt, it’s called your Profile. The file name varies depending on your operating system and version, but you can find it quickly by opening a prompt and typing $profile like so:
Now if you’ve got a brand new environment, this file may not even exist. You can test if it does, and then create it if it does not with the following commands:
The first command ensures that the you don’t already have a profile. If it returns true, the skip the second command.
The second command created the profile, as a file, and uses -force to create any directories required to create the item along the way. This command will work even if you don’t have a WindowsPowershell directory in your Documents folder.
What do I put in a $PROFILE?
Things you don’t want to type over and over again, of course. Don’t Repeat Yourself (DRY). Now, in reality you don’t want your profile to become just a giant function library, we have a concept called Modules for that, which we will discuss in just a minute, but there are some things which belong in your $PROFILE.
The Prompt
There is a special function called Prompt which you can define, that controls how what your command prompt looks like. You may have noticed that during this article I’ve had a very basic prompt that was just >, but most of you likely have a prompt that looks more like this PS C:\Source>. There is no trickery, I just wanted to make my prompt minimalist for these articles, so I typed the following:
12
PS C:\Source> function prompt { "> " }
>
As you can see, instantly my prompt was set to the minimalist version you’ve seen in all these articles. How is the default prompt defined? Let’s see, shall we?
So this prompt is defined as PS followed by the expression $executionContext.SessionState.Path.CurrentLocation which gets the current location of the execution context (aka the directory you’re in). Then, it displays one > for every level of $nestedPromptLevel, adding one. Well if your like most people, you’ve likely got no idea what the heck $nestedPromptLevel is. We will discuss it further, but for the most basic idea, there is a command called $Host.EnterNestedPrompt() which creates a new prompt. Like so:
As you can see, each nested level of prompt adds a >, which makes perfect sense given the above prompt function definition.
Location
Your current working directory is on display in the prompt at all times, and you know if you want to change that directory, you use cd. It must be named cd, both DOS and LINUX agree on this, how could it possibly be named something else, right?
123456
PS C:\Source> cd Highway
PS C:\Source\Highway> alias cd
CommandType Name ModuleName
----------- ---- ----------
Alias cd -> Set-Location
Well, as you can see, in PowerShell, which cd is an alias that exists by default for it, the actual command you’re execution is Set-Location. Well, most programs would rightly assume that whatever you can Set- you can also Get-, right?
12345678910111213
PS C:\Source\Highway> Get-Location
Path
----
C:\Source\Highway
PS C:\Source\Highway> alias -Definition Get-Location
CommandType Name ModuleName
----------- ---- ----------
Alias gl -> Get-Location
Alias pwd -> Get-Location
Yup, Get-Location returns the current Path we are at. You can see that we have two aliases defined by default for us, one is just shorthand for Get-Item, and the other is a helper alias for our Linux friends, who use pwd (short for Print Working Directory) to accomplish this same task.
Time to get pushy
Now, as it happens, in PowerShell (and Linux, and DOS) there are a couple of commands for working with Location that most people didn’t learn when they were first struggling through how to work at a command prompt. These two commands are called pushd and popd in Linux and DOS, but in PowerShell those are, of course, just aliases:
123456789101112
PS C:\Source> alias pushd
CommandType Name ModuleName
----------- ---- ----------
Alias pushd -> Push-Location
PS C:\Source> alias popd
CommandType Name ModuleName
----------- ---- ----------
Alias popd -> Pop-Location
So Push-Location and Pop-Location are commands that let you quickly leave your current location, but then return there very quickly. Let me demonstrate:
So initially, pushd would appear to just be a longer version of cd, it moves our current working directory to whichever directory we name. But, when we then invoke popd the magical nature becomes clear. When we invoke pushd it changes our directory, but puts the directory we’re leaving on a stack of remembered directories. A stack, hence push and pop.
As we pop the locations back off the stack, we are transported back to that location as our current working directory. Pretty darn useful if you need to move from one path to another and back very quickly.
PSDrive
Now, Location is all well and good, but that described where you are a given drive. My default drive, and likely yours, is C: aka the C-Drive. From time immemorial this has been the default hard drive letter in Windows. A: and B: were reserved for Floppy drives. Hard drives started at the letter C and incremented from there. But, that has been simply default for a long time now.
In PowerShell, I can still use C: and D: to move between drives. This next set of commands will only work if you have two drives (or an SSD and a Flash card as I’m using on my Microsoft Surface Pro):
As you can see, the commands move me between those two drives. But in reality, the concept of a drive has been much expanded in PowerShell.
If it has hierarchy (aka Locations) you want to Navigate, or items you want to inspect, then in PowerShell someone will likely have made it a drive.
There is a command in PowerShell that lists all current drives:
123456789101112131415
PS C:\Source> Get-PSDrive
Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Alias Alias
C 78.10 32.42 FileSystem C:\ Source
Cert Certificate \
D 3.29 56.16 FileSystem D:\
E FileSystem E:\
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan
blinkblink … Ok, so that is more drives than I was expecting when I first invoked this command. So what all drives are those, and how do I use them?
Enter Set-Location, aka cd:
12345678910
PS C:\Source> cd alias:
PS Alias:\> ls | select -first 5
CommandType Name ModuleName
----------- ---- ----------
Alias % -> ForEach-Object
Alias ? -> Where-Object
Alias ac -> Add-Content
Alias asnp -> Add-PSSnapin
Alias cat -> Get-Content
Here I’ve Set-Location to the Alias drive, and listed the first 5 items. Each PSDrive has different contents depending on what it is representing. Here’s a sum-up of the contents of the default set of drives:
C, D and E drive are File System drives, representing your various mounted drives. In my case they are my SSD, Flash card, and virtual CD drive.
Cert represents your digital certificate store, both CurrentUser and LocalMachine, which are the two root locations.
Env represents your Environment Variables, which contains all defined environment variables for your machine.
12345678910
PS Cert:\> cd env:
PS Env:\> ls | select -first 5
Name Value
---- -----
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\Tim\AppData\Roaming
asl.log Destination=file
ChocolateyInstall C:\Chocolatey
CommonProgramFiles C:\Program Files\Common Files
Function represents all functions defined in PowerShell, and in fact is how I showed you the definition of prompt earlier in this chapter (go ahead, look back, I don’t mind)
HKCU and HKLM represent your register, and specifically the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE sections of it. For instance, want to know all versions of the .NET Framework 4.0 installed on your box?
Variable represents all current variables defined in your scope.
1234567
PS Env:\> ls Variable:\ | select -first 3
Name Value
---- -----
$ Get-PSDrive
? True
^ Get-PSDrive
WSMan represents the “Windows Remote Management” aka WinRM settings.
Moreover, these are just the beginning. Lots of modules, which we are about to discuss, create even more drives. With the right modules you can browse around Active Directory, SQL Servers, IIS Websites, and so much more.
Modules Basics
Modules are a way to expand your available functions, drives, etc in PowerShell, but in an optional manner. Any given PowerShell environment can load many different Modules, in and adhoc manner. You can get a list of the current Modules you’re running as so:
As you can see, I have four modules loaded at the current time. But those are just what I have loaded. What I have available to me is quite another thing. If you type Get-Module -ListAvailable it will show you all of your possible options, but that output is large. I’m going to limit it somewhat here:
As you can see, I have a number of Modules installed, and they are installed by in the WindowsPowerShell\Modules folder of my Documents folder. But as I said, there are alot of them:
123456789
> Get-Module -ListAvailable | measure
Count : 62
Average :
Sum :
Maximum :
Minimum :
Property :
62 in fact, on my box alone, and it isn’t part of a domain, or a server, or one of many other things which might add to that list.
Creating your own modules
You can create your own modules very simply. A module is just a PowerShell script, named .psm1 instead of simply .ps1 and which loads up a series of functions, cmdlets, aliases, etc. The big additional requirement is that the script must also declare what it intends to make available to those who Import that module. Simply defining a function in a script isn’t enough, you must also Export that function to those who use the module. This is done with the Cmdlet Export-ModuleMember.
I’m not going to go into details here about how to create a PowerShell module, there is alot of information out there on that already. If you’d like to see the source of one, check out either my PowerShell repository, or the repository for Pester.
To use a module you have installed, simply type:
1
> Import-Module <name>
Must-Have Modules
The community of developers and administrators in the world being the wonderful geeks that they are, there are many awesome Modules that have been made available for others to consume. While it saddens me to report that there is not one consolidated repository, like NuGet for references, there are several good places. Both NuGet and Chocolatey have PowerShell modules hiding in their directories, but in my opinion the best overall implementation for PowerShell is PsGet.net.
PsGet
PsGet is the module that drives access to the PsGet.net directory of modules. To get started with it, simply type:
This will download and install the PsGet module. Once it’s installed, go ahead and import that module:
1
> Import-Module PsGet
You now have two powerful commands are your disposal:
- Install-Module
- Update-Module
With these, you can install any module from the PsGet.net directory with just one command.
Pester
I’m a big fan of TDD/BDD and so I was sold the moment Pester was described to me as a BDD framework for PowerShell. It allows me to test my modules with the familiar Describe, Context, It syntax. This module was created by the awesome Scott Muc and I’ve used it in my own PowerShell work. Details on how to use it can be found at the GitHub wiki for the project, and on Scott’s blog.
12
> Install-Module Pester
> Import-Module Pester
PowerShell Community Extensions
So what happens when lots of people love PowerShell and start putting together their greatest hits functions and CmdLets? PowerShell Community Extensions (PSCX) or course! Think of this as a -contrib project for PowerShell. It has functions that do all sorts of things, from awesome, to cute. How many commands? 148 as of this writing. Everything from Out-Speech which voice outputs any piped content, to quick helpers like Set-ReadOnly and Set-Writeable.
So Agile.NET Houston is coming up soon, and I’ll be there speaking as part of the Quartermaster track. If you’d like to attend, we still have some spots available, and you can use the discount code IEFriends50 to get 50% off the cost of registration, bringing it in at just $75.
We’ve been using it already quite a bit in the past chapters, but lets take a moment and introduce, properly, the pipeline. Pipeline’ing is powered in PowerShell using the pipe operator |. It passes data from one command, to another command. That other command had better be able to use that data. How? Well there is not magic here, there is conventions instead.
Let’s take a look at the help for our friend Get-Item, we do that as by typing help Get-Item or in our case help Get-Item -Parameter Path which is asking for the help for the Path parameter specifically:
1234567891011121314
> help get-item -Parameter Path
-Path <String[]>
Specifies the path to an item. Get-Item gets the item at the specified location. Wildcards are permitted. This
parameter is required, but the parameter name ("Path") is optional.
Use a dot (.) to specify the current location. Use the wildcard character (*) to specify all the items in the
current location.
Required? true
Position? 1
Default value
Accept pipeline input? true (ByValue, ByPropertyName)
Accept wildcard characters? true
Did you not get this? You likely need to install the help, run Update-Help and it will do so. If you did get this, you’ll see the line that talks about Accept Pipeline Input? and that it states true but more importantly that we can pass either ByValue or ByPropertyName. Let us explore both of those for a moment.
By Value Pipeline’ing
ByValue pipelines are the easiest to understand, in this case we can see from the help above we, the value for Path is expected to a String[] (a string array).
So here we have taken a directory listing, which is objects as we have learned previously, and then done a ForEach-Object on that to select just the FullName property. FullName is a string, and so we are sending an array of strings out to the console currently. How, lets send that same data to Get-Item:
Wait … uhm … what? Sure, we just took a bunch of FileSystemInfo objects and dumped them to the console, you know how that formats them? As a directory listing of course. But that means we’ve been successful in binding that data to Get-Item. Prove it? Ok…
So here we have created a bunch of Hashtables that contain a property named Path. Now this is to simple, it doesn’t make that point that we could have other data included in these hashtables. So I’m going to add some of that, but limit the number of files:
12345678910111213
> dir *.ps1 | %{ @{ Path=$_.FullName; Size=$_.Length; Updated=$_.LastWriteTime} }
Name Value
---- -----
Path C:\source\Highway\MVC\make.ps1
Size 211
Updated 5/4/2013 11:11:03 AM
Path C:\source\Highway\MVC\push.ps1
Size 62
Updated 5/4/2013 12:16:29 PM
Path C:\source\Highway\MVC\setv.ps1
Size 332
Updated 5/4/2013 11:26:16 AM
Ok, three entries, each with three properties, and we’re good … Right? sigh No. So you’ll see from the output, these are not properties. They are entries in a Hashtable, and are outputted vertically under Name and Value because of this. We can easily turn this into a real object with properties though, using a cast to PSCustomObject which is the PowerShell dynamic object.
Alright, now we have the horizontal labels for our properties, and values below that. Awesome. Now lets pipe that to Get-Item:
1234567891011
> dir *.ps1 | %{ [PSCustomObject]@{ Path=$_.FullName; Size=$_.Length; Updated=$_.LastWriteTime} } | Get-Item
Directory: C:\source\Highway\MVC
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 5/4/2013 11:11 AM 211 make.ps1
-a--- 5/4/2013 12:16 PM 62 push.ps1
-a--- 5/4/2013 11:26 AM 332 setv.ps1
Bingo, we bound Path to Get-Item. That gives you an example now of both types of Pipeline’ing.
Functions
Now that we understand pipelines, how do we start to create reusable functionality? Well, to do that we need to write functions. And so, lets look at this in practice with everyone’s favorite demo … Hello World!
Basic Script Blocks
We can create a script block simply by using a set of curly braces { }. Like so:
12
> { "Hello World!" }
"Hello World!"
That output is kind of odd, right? It didn’t output the string, because that would not have the quotes. What type of object did that return?
Yep, both of those do indeed execute, we lose the quotes, and all is well. So we now have a code block.
Named Functions
But what if I want to name that script block? Easy, we define a function:
12
> function HW { "Hello World!" }
>
Done, we’ve defined that block now as HW. How do I run it? I type HW of course!
12
> HW
Hello World!
Now I can assign a script block simply to a variable if I want, but if I do so, then I still need to use & or . to execute it, where-as functions are called by name. See:
But functions also have an important other aspect, which is that they can have parameters. So let’s create a function which takes a parameter, but lets say we want to pass it a location:
Now, we can specify types for parameters, so that we can’t pass bad data:
12345678910111213141516
> function HW {
>> param([int]$location)
>> "Hello $location!"
>> }
>>
> HW Dallas
HW : Cannot process argument transformation on parameter 'location'. Cannot convert value "Dallas" to type
"System.Int32". Error: "Input string was not in a correct format."
At line:1 char:4
+ HW Dallas
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [HW], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,HW
> hw 123
Hello 123!
See that we got an error now when we passed the Dallas string, but when we passed 123, we succeeded. Now we can change this pipe in an array, passing ByValue:
12
> 1..5 | HW
Hello 0!
Huh… that didn’t do what we expected. I guess we’ll have to give a hint that we want that Parameter to be pipelined.
Ok, but still not “correct”. Why? Because as it happens, we’re using the simple form of a script blocks. A script block is actually defined by three sections: Begin, Process, and End. By default, if we don’t specify a section, we get End. What are the differences? Begin runs once, before pipleline values are bound. Process is run once for each member of the pipeline. End runs after all members have been process. How do we know that we get End by default? Look at the value we got, it was the last value of the pipeline.
So here we have redefined our function, and given it a Begin, Process and End block. And we can see that $location, because it is marked from pipeline, is not set until we are in Process, and then we run process 5 times, and finally we run ending once.
Branching
So… it is not programming without if blocks, right? Well we’ve got those:
In PowerShell we have a concept called Cmdlets, these are the functions we use. We’ve already seem some of them, but this chapter will introduce you to the must-know Cmdlets. This is not a catalog of all Cmdlets, not even close. As of PowerShell 3.0 there are 2,430 in Windows Server 2012, without adding those available from the community.
Microsoft’s commitment is unfailing, they’ve committed to shipping PowerShell Cmdlets for every server product. If you use SQL Server, Exchange, BizTalk, SharePoint or any of the other server products then you simply cannot do anything more powerful to pump up your career than to learn PowerShell.
Proper Grammar
Cmdlets have a grammar all of their own. In PowerShell we are encouraged to use a grammar of Verb-Noun when creating Cmdlets and functions. But more than that, there is a list of common verbs, which help new users discover your functions. For instance, I created a function to update the value of an AppSetting in a web.config or app.config file. Now, I’ve not memorized the whole list of verbs, so how did I know which one to use? Well, I used the Cmdlet called Get-Verb like so:
Hmm… I wonder if it should be called Create-AppSetting:
12345678910111213141516
> Get-Verb C*
Verb Group
---- -----
Clear Common
Close Common
Copy Common
Checkpoint Data
Compare Data
Compress Data
Convert Data
ConvertFrom Data
ConvertTo Data
Complete Lifecycle
Confirm Lifecycle
Connect Communications
Nope, no listing for Create. How about Set-AppSetting:
12345678910111213141516171819
> Get-Verb S*
Verb Group
---- -----
Search Common
Select Common
Set Common
Show Common
Skip Common
Split Common
Step Common
Switch Common
Save Data
Sync Data
Start Lifecycle
Stop Lifecycle
Submit Lifecycle
Suspend Lifecycle
Send Communications
Alright, yep, that could work. But I’m curious, how about Update-AppSetting?
12345678910111213
> Get-Verb U*
Verb Group
---- -----
Undo Common
Unlock Common
Unpublish Data
Update Data
Uninstall Lifecycle
Unregister Lifecycle
Unblock Security
Unprotect Security
Use Other
Bingo, Update-AppSetting is a good choice, so is Set-AppSetting. I chose Set-AppSetting, but either would have been an excellent choice.
Likewise, if you were to look-up Delete:
12
> Get-Verb Delete
>
Nope, not there. How about Erase?
123
> Get-Verb Delete
> Get-Verb Erase
>
Nope again. How about Remove?
1234567
> Get-Verb Delete
> Get-Verb Erase
> Get-Verb Remove
Verb Group
---- -----
Remove Common
There it is! So remember, use Get-Verb when deciding how to name things, it will help everyone out in the long run.
For-Each
So what is the most important Cmdlet in PowerShell? Well, for sheer utility, I’ve got to give this award to ForEach-Object. It allows you to iterate over any array or list of data. So how do we use it?
Alright, we’ve got one call to the script block (inside the { }) for every member of the array. Now, you might be thinking, “man that is really verbose for a scripting language”, well good news that is the really long form version of that command. Shall we terse it up a bit?
First, ForEach-Object has an alias (more on those later) in simply %. So we can shorten it up like so:
Pretty good, but we can get even better. We’re explicitly calling Write-Host, but whatever is returned at the end of a command is automatically printed to the host. So we can shorten it further like so:
Alright, I can hear you already, hold up Mr. Smarty Pants, you just did something tricky there. Yep, I sure did. How did that work? Let me explain. Any string in double-quotes (" ") will have any variables ($foo) inside of it replaced with the value of that variable.
Moreover, any script block returns the last object it creates by default, so since that script block creates a string, it returns that string. And ForEach-Object collects those objects and returns them as an Array, here to console, but it could also be piped to yet another Cmdlet or function. But, the really attentive among you will be saying, “Wait! You slipped in another $.” Your right, but lets see it without that extra $.
Ah, you see, this version doesn’t actually perform the multiplication. It replaces the $_ with each value, but the rest is just considered a string. But PowerShell has a way to evaluate expressions in the middle of strings as well, using $( expression ). So the extra $ in this 1,2,3,4,5,6 |%{"$_ $($_ * $_)"} version evaluates the multiplication and gives us our “most terse form” of this command.
Where-Object
So we’ve now seen how to iterate over an array, but the other thing we usually need to do is to filter them. In .NET, we are used to using LINQ for this, but LINQ is pretty verbose itself. How about we cut down our list of numbers to just the even numbers using Where-Object:
Now, we’ve seen how to limit the array, but here’s a little diversion. At the current time we’re returning an array of strings. Actually, since all arrays in PowerShell are arrays of Objects (in C# Object[]), this would be an array of objects consisting entirely of string objects. Prove it? Sure. First the type of the array itself:
But what if I wanted to have access to each of those numbers (the number itself, and the square) at the end of the command. One way to do this would be to create a Hashtable instead of a String like so:
12345678910
> 1,2,3,4,5,6|?{ ($_ % 2) -eq 0 } |%{@{Num=$_;Square=$_ * $_}}
Name Value
---- -----
Num 2
Square 4
Num 4
Square 16
Num 6
Square 36
But sometimes have to name variable when you don’t intend to use those names is a bit annoying a verbose. So instead, we can create an array by simply using the ,@( ) array constructor syntax:
Boom, Int32s for the win. Instant multi-dimensional array. This is powerful, it is a terse syntax which is similar to Tuples in other languages. Because they are Object[] arrays, the types don’t have to match. Oh yeah, did I mention there is a short form for creating arrays of concurrent integers? Ohm, my bad. For instance:
The last Cmdlet I want to introduce in this chapter is the one most people use without even knowing that they’re doing so. If you’ve every opened a PowerShell command prompt, you’ve likely done something like:
1234567891011121314
> dir
Directory: C:\Source\Highway
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/2/2013 2:20 PM Data
d---- 5/4/2013 10:44 PM MVC
d---- 5/4/2013 6:37 PM Onramper
d---- 5/4/2013 6:46 PM Services
-a--- 5/4/2013 11:59 AM 1062 dest
-a--- 5/4/2013 12:11 PM 385 distribute.ps1
Or perhaps if you’re from the bash or other sh descendant family of shell users:
1234567891011121314
> ls
Directory: C:\Source\Highway
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/2/2013 2:20 PM Data
d---- 5/4/2013 10:44 PM MVC
d---- 5/4/2013 6:37 PM Onramper
d---- 5/4/2013 6:46 PM Services
-a--- 5/4/2013 11:59 AM 1062 dest
-a--- 5/4/2013 12:11 PM 385 distribute.ps1
Now, in reality you’re using a Cmdlet called Get-ChildItem. Prove it? Sure:
Now this Cmdlet has so much power it almost deserves a chapter to itself. Let’s review just a few things that can’t be skipped over. First, this Cmdlet returns an array of FileSystemInfo objects. Of course that’s easy to prove:
That means we have access to all sorts of data about those directory items by pipeing that command along. For instance, what if I wanted the full path and filename?
1234567
> ls |%{$_.FullName}
C:\Source\Highway\Data
C:\Source\Highway\MVC
C:\Source\Highway\Onramper
C:\Source\Highway\Services
C:\Source\Highway\dest
C:\Source\Highway\distribute.ps1
And if I wanted to get just the files?
123
> ls -File |%{$_.FullName}
C:\Source\Highway\dest
C:\Source\Highway\distribute.ps1
And if I wanted their sizes instead?
123
> ls -File |%{$_.Length}
1062
385
Another bonus section? Oh, ok…
We can restrict the types of files to a pattern like so:
12
> ls -File *.ps1 |%{$_.Length}
385
What if I wanted that same thing, recursively, through every subdirectory of my current location?
> ls -File *.ps1 -Recurse|%{$_.Length}|Measure-Object -Sum
Count : 34
Average :
Sum : 38979
Maximum :
Minimum :
Property :
Aliases
There are a finite number of keystrokes left in your hands before you die. – Scott Hanselman
So, you’ve likely picked up by now that I’m a fan of terse commands. Terse commands allow you to move faster, which to me is a huge part of why I’m investing in PowerShell. There is an ability in PowerShell to create shorter versions of Cmdlets, as you’ve seen already in this article, called Aliases. There are alot of aliases already defined. How many? So many I can’t just do a screen shot of them, but I can count them:
123456789
> alias | Measure-Object
Count : 150
Average :
Sum :
Maximum :
Minimum :
Property :
150 aliases already defined for you. If you want to see what command is behind something like dir you can simply:
12345
> alias dir
CommandType Name ModuleName
----------- ---- ----------
Alias dir -> Get-ChildItem
As you can see, dir is Get-ChildItem. What if I wanted to see all aliases for a given Cmdlet?
1234567
> alias -Definition Get-ChildItem
CommandType Name ModuleName
----------- ---- ----------
Alias dir -> Get-ChildItem
Alias gci -> Get-ChildItem
Alias ls -> Get-ChildItem
Now, aliases are something you can expand on! You can make it super easy to open text files by aliases notepad.exe as so:
12
> New-Alias n C:\Windows\system32\notepad.exe
> n .\distribute.ps1
That opens Notepad, with the distribute.ps1 file already opened for editing. I keep aliases around for a lot of things. For my text editor, my text comparison tool, and so much more.
I must go down to the seas again, to the lonely sea and the sky,
And all I ask is a tall ship and a star to steer her by,
And the wheel’s kick and the wind’s song and the white sail’s shaking,
And a gray mist on the sea’s face, and a gray dawn breaking.
– Sea Fever by John Masefield
Every developer knows that in order to be successful at their chosen profession, they need to keep the best tools at their disposal. We all have our favorite text editors, and our favorite comparison tools, and the wise among us also have our favorite scripting languages and command line environments.
I am an unabashed fan of GIT, and as such for several years now I’ve used the bash shell as my command line environment of choice. But I recently started paying more attention to PowerShell and I realized that I had not at all given it it’s due when I first learned about it several years ago. I’ve spoken recently with @DevlinLiles, @AmirRajan, @CoriDrew, and @BForrest about this, and I realized that I wasn’t alone at all in this. Most developers working in .NET languages have mostly ignored PowerShell. I intend this series of blog posts to correct this issue.
The Basics
Let’s start at the very beginning
A very good place to start
When you read you begin with A-B-C
When you sing you begin with do-re-mi
– “Do-Re-Mi” by Rodgers & Hammerstein
PowerShell 3.0
So how do I use the PowerShell thing, Tim? Easy. First, we need to know what version of Windows you’re using now, because we might want to upgrade you to the latest version. If you’re using Windows 8 or Windows Server 2012 then you’re good, you already have PowerShell 3.0. If you’re using Windows 7 or Windows Server 2008 or Windows Server 2008 R2, then you need to download the Windows Management Pack 3.0 which upgrades you to PowerShell 3.0.
Not sure if someone else might have already installed it? Just open PowerShell (hint: Win+R -> PowerShellenter) and enter $host.version at the prompt.
12345
> $host.version
Major Minor Build Revision
----- ----- ----- --------
3 0 -1 -1
The above it what we’re looking for, anything else, and you need to install the Windows Management Pack 3.0.
Variables
The first thing you need to know about PowerShell is how to create a variable. This is very simple, you just assign it to a variable name. In PowerShell, all variables are preceded by a $. So if you want to create a variable X and assign the integer value 1 to it, you would type:
1
> $X = 1
Important to know, especially for C# developers, is that PowerShell is case-insensitive. As such, $X is the same as $x.
Value Types
Now, .NET developers, pay attention to this. In PowerShell all variables are actual objects, not just string values. What do I mean? Type this:
Holy smoke! That variable is an Int32, I mean a real System.Int32.
Because of this, we can use any type of methods that might exist on those objects. For instance, we could type:
12
> $X.Equals(4)
False
So how do we create non-value types then? That depends…
Reference Types via New-Object
Most of the time, we are used to creating .NET objects by typing something like var dt = new System.DateTime() but in PowerShell we have something similar, but different:
1
> $dt = New-Object System.DateTime
You can always check the value of a variable, just by typing it’s name at the prompt like this:
123
> $dt
Monday, January 1, 0001 12:00:00 AM
That makes total sense, that is the default value of a DateTime aka default(DateTime) in C#. But in reality, I tend to use System.DateTime.Now to get the system time, more often than I do new DateTime(), so how to I do that in PowerShell?
Reference Types via Static Properties & Methods
So if we want to access the .NET Framework’s static types, we simply need to reference the type, and then the method, as follows:
123
> [System.DateTime]::Now
Monday, May 6, 2013 10:22:26 PM
Now, if we wanted to assign that to our variable, we would just do:
1
> $dt = [System.DateTime]::Now
Please note, when we assign the value to a variable, we no longer get output to the console. We’ll see how to change that in just a bit.
Arrays
Arrays are common in all programming languages, they represent a series of values. In PowerShell, those values are not required to be of the same type, you can think of all Arrays in .NET terms as System.Object[], an array of Objects.
Declaring and using arrays could not possibly be easier in PowerShell, we simply put together a series of values, separated by commas.
1234
> 1,2,3
1
2
3
As I noted above, they don’t have to be of the same type:
12345
> 1,"abc",[System.DateTime]::Now
1
abc
Monday, May 6, 2013 10:28:15 PM
And that is all there is to arrays. You can add members to arrays many ways, but the simplest is as follows:
There is one other type of object which is critical to the world of PowerShell, and that is the Hashtable. PowerShell is a dynamic language, in fact as of 3.0 it’s even built on top of the Dynamic Language Runtime, but as such it needs a flexible structure for storing loosely types objects. Enter the Hashtable.
The syntax for Hashtable couldn’t possibly be easier, to create one you just use @{ key=value; key2=value2} So for instance, if you want to create a Hashtable to store a bunch of people, you could do so like this:
Now, as we learned in the last section, we can create an array just by separating items by commas, so lets do so, and then sort these people by FirstName:
12345678910
> $tim,$cori,$barry | Sort-Object FirstName
Name Value
---- -----
LastName Forrest
FirstName Barry
LastName Drew
FirstName Cori
LastName Rayburn
FirstName Tim
As you can see, Barry is now listed first, then Cori, then Tim. Don’t worry about understanding Sort-Object just yet, we’ll get into how that line works more in the next post.
Now, lets imagine I want to add a value for Employer to each of these. How to I change a Hashtable once it has been created? Easy, just refer to a property that doesn’t exist yet, and set its value.
In addition to all of the above, there are a couple of constants which you might want to know about when developing. $null is the constant value of a Null Reference. In addition there are constants for $true and $false though if a boolean is expected you can also always use 1 or 0 respectively.
Lately I’ve been developing on a side project using the awesome Azure Mobile Services offering from Microsoft. Specifically I’ve been developing a Windows Phone 8 application, the details of which will be revealed in time. One of the best features of Azure Mobile Services is the ability to work with a Dynamic Schema, it will automatically insert new columns for fields it has never received before.
There are many great reasons for this during development. It allows for rapid iteration, which is great. But, let’s take the example of the Todo Hands On Lab, and look at the DataContract established for it’s entity.
If I change nothing else other than this, I when I run my program I’d expect that the Description column would be added to the database when I saved a new item. But, instead, I get the following exception when I save an item:
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Error: Unable to insert a null value for new property 'description'
Source=Microsoft.Azure.Zumo.WindowsPhone8.Managed
InnerException:
I was more than a little baffled by this concept, my first read of this exception got me thinking things like: ”who on earth would design a dynamic data feature to create NON NULLABLE FIELDS?!?!?” and other less kind statements. Well, as they say, pride commeth before the fall. As I’ve researched this error, I’ve realized it’s entirely reasonable. Why? Ah… REST.
Azure Mobile Services data offering is built as a set of RESTful services, using JSON serialization. That means that initially my request to add an entry named “Foo” would have looked like this:
12345
{id:0,text:'Foo',complete:false}
When I added the additional field but didn’t set a value for it, the serializer added it to the submitted output, resulting in:
123456
{id:0,text:'Foo',complete:falsedescription:null}
Sure, that makes sense … Unless your the SQL Server who is now being asked to add that new field. Why? Because you’ve got NO IDEA what the data type of description is. Whoops! So how do we solve this? Well, there are a couple of ways we can do that.
We could add the field manually in SQL Server, specifying the data type desired. This works great, but kindof unravels the whole point of Dynamic Schema.
We could put in temporary code, so that the first time we send this up, it’s populated. After that, the field is nullable so there is no problem storing nulls from that point onward. I’m not a big fan of “secret recipes” in code bases, and this model leaves no trace for the next guy of the “proper procedure” so I decided against it.
We could add a Setup script, which pushed a single completely populated entity. This could be run all sorts of ways, from a unit test to a rake task, but would ensure the schema desired. This solution is better, but still a little buried for me.
We could make the DBAs amongst us cry, and decide that our entities will provide a default value for reference types such as string (note value types don’t have this problem, they can’t be null) in the constructor of our type. This technically takes more space, and I’m certain the DBAs will yell at me about other reasons, but on the other hand it leaves a clear pattern to be followed by future developers.
So you want to do Windows Phone 8 development on a Mac, the traditional answer to this has been, your out of luck. The hurdles are two fold:
The Windows Phone Emulator has always, since Windows Phone 7, been run as a HyperV virtual machine. This means if your running Windows itself inside a VM, running the emulator is like trying to run a VM inside a VM. This has traditionally been an unsupported scenario.
The Windows Phone 8 Emulator raised the bar again, because it only runs on Windows 8. That causes two problems for us. The first is that Boot Camp hasn’t been updated to support Windows 8 yet, so we can’t (easily) get the necessary drivers for our Mac to run Windows 8.
The second problem that Windows 8 requirement brings us is that HyperV in Windows 8 requires “Second Level Address Translation” support from it’s CPUs. That means the CPU its running on has to support very new virtualization support in order to run. That will make it even more difficult for a VM solution to work for us.
But fear not my valiant friends, for there is an answer. VMWare Fusion has heard your cries, and there is a way to solve this problem. Here are the necessary steps, care of an awesome MSDN forums post:
Using VMWare Fusion 5 or better, create and install a Windows 8 virtual machine. If you have one already, your fine.
Stop the virtual machine by shutting down Windows 8.
At the VMWare Virtual Machine list, right click Windows 8 machine then click “Show in Finder”.
Right click the file then click “Show package contents”, then find and open with a text editor a file with the extension .vmx
Go till the end of the file and add this two lines (first check whether they were previously added):
hypervisor.cpuid.v0 = "FALSE"
vhv.enable = "TRUE"
At the VMWare Virtual Machine list, right click Windows 8, click “Preferences” then “Advanced”. Choose “Intel VT-X with EPT” as “Preferred virtualization engine”.
Start your virtual machine, launch Visual Studio, and develop away. The emulator will happily run.
Obviously this solution is a “It works on my machine” situation, but I’m sure you will find success down this path.
Does your processor have to support SLAT? Yes, your physical hardware must be current enough to support SLAT. For Macs, this means you need to be running an i5 or i7 mac.
What hardware are you running? As of today, I’m running this solution on a Thunderbolt MacBook Pro running a 2.3 Ghz i7 and Lion, not Mountain Lion. The official Model Identifier for my mac is MacBookPro8,3.
On October the 22nd, at the Microsoft Offices in Houston, we will be hosting a Windows Azure Developer Camp. We will be covering all of the basics of Windows Azure, from IaaS to Websites, from SQL Azure to Mobile Services. And what’s more? We’ve got some rockstar trainers for you. Todd Girvin, Allen Hurst, Devlin Liles, Chris Weldon, Ben Floyd and myself will guide you through all the hands on labs, and you’ll leave ready to bring the incredible scale and ease of Windows Azure to your next project.
While you’re there, be sure to ask about our incredible new Houston offices. Need consultants in Houston? We’re open for business and ready to help. Looking for a new job? Drop me a line, and we’ll talk about the opportunities for you to start improving.
Even if none of that is true, be sure to ask us that day about our upcoming Monday Night Football event.
I’m thrilled to announce that Microsoft has deemed fit to award my efforts over the last year with a Microsoft MVP for Connected Systems Development, once again. This marks my sixth year as an MVP, a community of such passionate leaders, contributors and influencers that it could boggle the mind. Every MVP is different, but each brings a passion about their technology that is infectious.
I look forward to once again getting the chance to visit the Microsoft campus during the MVP Summit, and to continue to help start conversations everywhere I go. I’m also thrilled to announce that Devlin Liles, my co-author for Entity Framework 4.1 : An Expert’s Cookbook, was also re-awarded today as an MVP for Data Platform Development. With that, I’ll let you get back to your day, and I’ll get back to celebrating my wife’s birthday which is also July 1st and which she has shared the celebration of my award for the last six years.