HOWTO: Custom PowerShell Error Handling

Today I was asked to produce the email addresses of a few thousand employees based on the First Name and Last Names provided by HR.  Easy, right?  Well it would be except of course for the many edge cases where the name HR has for an employee is completely different than what is actually recorded in Active Directory.  Realizing I was going to have a problem with many failed addresses, I had to come up with an easy way of producing a list of the failed addresses along with those that I was able to match.  In doing so, I figured out how to solve a long standing frustration with PowerShell and wanted to share.  Consider this scenario where you want to see if a mailbox exists.  You run get-mailbox “Mike Smith” | select name


The mailbox exists so you get an object back and everything looks great.  Now however imagine if you search for a mailbox that doesn’t exist.  What happens?


You get the wall of red text that is synonymous with PowerShell errors.  In this case however, we only need to know the user name that failed.  We don’t need any of the other text.  How can we accomplish that?

It turns out that most cmdlets support a parameter called –ErrorVariable.  The purpose of this is to simply store any errors that are generated by the cmdlet.   This should be used in conjunction with the –ErrorAction parameter where it would be set to “SilentlyContinue”.  In other words, if an error happens, don’t bug me about it but store the results in a variable.

Continue reading

HOWTO: PowerShell Tips and Tricks (Part 1)

I’ve been using PowerShell for a while now and in that time I’ve come up with a few tips and tricks that I find myself using a lot.  Below you’ll find a handful of commands I find myself using most often:


1) Run a command with elevated permissions

Ever needed to run a command from PowerShell as an administrator?  Of course you have.  Here is a neat trick that makes the process of process elevation easy.  I use this line below as a shortcut on my desktop to edit my local hosts file.

Start-Process notepad.exe-ArgumentList c:\windows\system32\drivers\etc\hosts-Verb RunAs

2) URI Validation

When you’re working on a script, you often need to validate if an input path is well formed.  This can be in the format of a webpage, an FTP site or even a path on the local file system (provided it’s in the format of file://).  Here is an easy way to validate if that URL is in fact correctly formed.  This is also an example of being able to call .NET classes directly (in this case the system.uri class)

if ([system.uri]::IsWellFormedUriString($URL,[System.UriKind]::Absolute)) { "Yes" } else { "No" }

Continue reading

Are you forward thinking enough?

"640kb ought to be enough for anybody." – Bill Gates, 1981

That quote, while Bill Gates claims is apocryphal has nonetheless become cautionary shorthand for a situation where you arbitrarily limit your design under the inevitable false assumption that no one will ever need to exceed your design specifications.  I suspect that this quote is at least partially responsible for the decision to make the IPv6 address space as large as it is.  Back in the day, the designers of IPv4 almost certainly could have been overheard saying, since the number was so seemingly impossibly large anyway:

"4,294,967,296 IPs ought to be enough for anybody."

Fast forward to the 21st century and it turns out that they were spectacularly wrong and this resource is now almost completely exhausted.  "So much for forward thinking" their successors almost certainly thought.  So when IPv6 came along, I swear they just dared people to quote them.  I mean just look at what this theoretical quote would sound like!

"340,282,366,920,938,463,463,374,607,431,768,211,456 ought to be enough for anybody."

Alright, so what is my point to all of this?  I recently ran into a situation at work that required that I better understand how Windows memory management works.  Through that research, I ended up working with a Sysinternals tool called RamMap.  This tool gives tremendous visibility into exactly how your RAM is carved up.  But of course to make use of the numbers, you need to understand them.  This lead me to a video on Channel9 for the series "Debug Tools".  In this video, they give a lecture on how to use RamMap.  If you’re at all interested in Windows troubleshooting, this is a fascinating video and I recommend it.  You can can that here.  This then led me to another Debug Tools video on VMmap which yet another wonderful tool from Sysinternals.  This one focuses on understanding virtual memory.  During the video, the presenter made an off handed comment about why VMmap reported that the total available virtual memory pool was "only" 8TB. He explained this was because the CPU designers (ie Intel and AMD) decided that even though they are building a "64 bit" CPU, that we aren’t going to actually assign all 64 bits to the pipeline to make designing the chips easier. 

Continue reading

HOWTO: Quickly create and iterate a GUI for your PowerShell script

Due to the nature of how PowerShell was designed, it actually offers direct access to the .NET framework which means we can do some pretty cool things.  For example, with only a relative few lines of code, we can create a full “Visual Basic” style GUI based application entirely in PowerShell!  The catch to this however is that you will likely typically be building this in your PowerShell IDE of choice such as the PowerShell ISE or PowerGUI — both of which are purely text editors.  This means that in order to “draw” the windows, you’ll need to figure out all of the x,y positions of all of the windows and their relationship to each other and… well that becomes a nightmare pretty quickly.  I decided to see how much of this process I could automate or streamline.  Now it’s worth mentioning that there are GUI based designers available such as Sapien PowerShell Studio that can drastically simplify the process.  Unfortunately this is a commercial application.  I wanted to see if I could find a free alternative.  After playing around, I came up with and solved for the following requirements:

1) Be able to use a GUI based tool to easily design the layout of my PowerShell GUI based application

2) Be able to define the layout of my form in a different file thus separating out the layout from the “business logic”

3) Be able to quickly change and iterate the layout of the GUI after it was initially created

4) Use only free tools to accomplish the above

Continue reading

HOWTO: Get Timestamp of a file from a remote FTP site using PowerShell

This HOWTO describes how to programmatically obtain the timestamp of a file on a remote FTP server.  This can be useful in situations where you only want to check, update or delete the newest or oldest files.  I opted to create a HOWTO for this as I found a large number of requests for this kind of thing in my initial Google searches to accomplish this but no clear answers.  I did eventually stumble upon a guy named Anmelden on the MSDN forums who posted a solution he used with .NET.  Since PowerShell has the ability to directly use .NET libraries, I was able to retrofit his solution to apply directly within Powershell.  The original post can be found here.

Now, before we jump into this, I’d like to quickly address one of the solutions that was commonly suggested in my original searches and that is to use the Windows FTP.exe command and extract the date that way.  I actually got that to work except for my cases anyway, it had one significant draw back:


You’ll note that, with my FTP server at least, it by default returns dates in the format MMM DD HH:MM.  You’ll note that the year is not returned at all and therefore it is not possible to do any kind of string manipulation to add the year.  With that out of the way, let’s delve into a working solution, shall we?

Continue reading

HOWTO: Resolve CID_MISMATCH error with VMware virtual machine

This HOWTO describes how to resolve a situation where a running virtual machine suddenly abruptly powers off and when you attempt to start it again, you are given the error “the content ID of the parent virtual disk does not match the corresponding parent content ID of the child”.

In this instance, a virtual machine called FSRVCLOAPP17 failed in the middle of the night.  An attempt to manually power the VM back on resulted in the error:


Continue reading

HOWTO: Write Chinese on a Computer Keyboard

Last year I wrote a post on how to write Japanese on a western style keyboard. You can find that HOWTO along with some fascinating backstory here.  As I was already comfortable with Hangul (Korean), that meant that of the “big 3” Asian languages, I had a (very) basic comprehension of how to write with 2 of them.  Well, I figured today seemed like a great day to tackle what is perhaps the most daunting one of all.  That’s right, that means this HOWTO is going to cover how to write Chinese on your western keyboard!  However, before we can delve into the mechanics of how the process works, we need to understand a little bit of the history.

Disclaimer:  Everything you are about to read is based on my time spent with Google and Wikipedia.  I’ve almost certainly got some or even much of this wrong so if you do see something I have incorrect, please let me know in the comments and I can update it.  

First and foremost, it’s important to know that according to Wikipedia, “Chinese” is not one cohesive language but is rather a collection of between 7 and 13 “language dialects” that collectively form the “language family” that Westerner’s tend to think of as Chinese.  Of these dialects, by far the most common is one you’ve almost certainly heard of and that is called “Mandarin.” But that’s not the only one.  There are other dialects such as “Wu”, “Yue”, and “Min”.  What’s fascinating about these is that they are what is described as “mutually unintelligible” languages.  That is to say, despite sharing similar roots, a speaker from one dialect will not be able to readily communicate with a speaker from another dialect.  Think Spanish and Italian.  Same Latin root, but if a Spanish person travels to Italy, they would have difficulty communicating.

“Standard Chinese” or that is to say the “official” language adopted by the Chinese government is based off of the “Beijing dialect” and is also known as Pekingese.  It is specifically adopted by the “People’s Republic of China” (PRC) along with the “Republic of China” (aka Taiwan).  It’s also one of four official languages in Singapore.  There is another subset of Chinese called Cantonese which is considered more of a “prestige” language and is the official language of Hong Kong.  The important thing to take away from this is that, at least as far as my research has revealed for the level of detail I require for this post, all of the languages above use effectively the same written characters.  That is to say, if you know what you want to say, you should be able to follow the steps below to write your electronic message in any of the possible Chinese dialects.

The next thing to keep in mind is that generally speaking, like Korean and Japanese, a character generally represents one spoken syllable. That is to say, each “block” should represent one syllable. Also like Korean and Japanese but seemingly taken much further is the fact that a block/character may be a word on its own or a part of a polysyllabic word.  As you’ve likely heard, Chinese doesn’t have an alphabet in the sense that Westerners are familiar with.  Often times, a character (aka a series of strokes) represents an entire meaning on its own.  Put another way, each character is an atomic unit and cannot be further broken down.  It is estimated that there are over 60,000 unique characters in the Chinese language.  The good news is that research has suggested that a college educated Chinese citizen only needs to know about 3,000 to 4,000 characters to be considered fluent.

Continue reading

HOWTO: The wrong way to use VMware DirectPath

Consider the following scenario:  You have a physical IBM server running Windows 2008 R2 with an LSI SAS controller PCIe card connected to an IBM LTO5 tape library and controlled via NetBackup 7.6.  You wish to obsolete the Windows 2008 server and move the SAS card onto a new IBM x3650 M4 server running ESXi 5.5.  Once that’s done, you wish to configure DirectPath to map the physical card to your new Windows 2012 R2 NetBackup VM.  At this point, there should be nothing in the story that sounds terribly difficult.  Physically move the card into the new ESXi host, configure DirectPath to allow the card for Passthru, reboot and you’re done.  Well, that WOULD be true… but only so long as if you pick the right check box.  It turns out the VMware DirectPath box can be much more dangerous then at least I first thought.  What do I mean?  Here is the screen I was presented with after installing the LSI SAS card.  The keywords in that sentence are LSI and SAS. 

See the keywords “LSI” and “SAS”?  So did I .  So I picked that one and pressed OK.


I was told I had to restart the host for the change to take effect.  So I did.  That turned out to be one of the stupider decisions I’ve ever made in my life.  Can you guess why?  Before we explain that, let me show you what I was greeted with after I rebooted the server.  ESXi booted fine except this is what I saw when I connected to it:


Continue reading

HOWTO: Backup and Restore FreeNAS Bootable USB Keys

I have several RAID5 NAS devices at home that are built upon the excellent FreeNAS.  One of the catches to using FreeNAS is that you must dedicate an entire drive to the operating system.  This means if you have say 3 1.5TB drives, you have to allocate (and therefore lose) 1.5TB of disk space to host a couple of hundred meg of operating system.  That’s obviously crazy and so the alternative is to simply boot off of USB.  I’ve been running this way for years and it’s been fantastic.  I got to thinking recently though – what happens if my USB key that I’m booting from fails?  I manually periodically backup the configuration so I can restore that but that only works once I’ve gone through all the trouble of rebuilding a new FreeNAS installation.  Wouldn’t it be easier if I could just clone the USB key and be done with it?

In my quest to do just this I discovered an excellent free piece of software called ImageUSB from Passmark. The software performed bit for bit duplication of a USB drive. It’s primary use case appears to be for mass duplication of USB drives (say to hand out at trade shows) but it has one feature in particular we want to take advantage of and that is the ability to save an image of a USB drive to a file.  Here’s how:

Continue reading

HOWTO: Quick and dirty Active Directory User Creation using Powershell

I had a situation where I needed to create a bunch of service accounts using pre-created complex passwords.  Now there are tons of Powershell scripts online to accomplish just this but in my brief searching they all seemed either too simplistic or far too complex.  So I decided instead to draft my own.  You can see the script is very simple.  You provide the username, password and description you want, run it and the accounts are automatically created and placed in the correct OU.

It’s beautiful in its simplicity. 🙂

Continue reading