Accessing a PowerShell Class Defined In A Module From Outside A Module

PowerShell 5 introduced the concept of classes. This is an exciting new feature that will really help promote code reusability. It seems natural then, that you would want to organize your classes into PowerShell Modules.

It’s not obvious though, how to use a class defined inside a module from outside that module. There are, in fact, three methods available to you.

Let’s say you have a module, MyModule.psm1. In it you’ve defined a class:

class MyClass
  [string] $MyString = 'My String Value'

  [string] GetSomeValue()
    return 'Some Value'


Simple enough. So how do we get to this masterpiece of class coding? The first technique has us creating a function inside the module. Within that function we return a new instance of the class.

function Get-NewMyClass()
  return [MyClass]::new()

# Export the function, which can generate a new instance of the class
Export-ModuleMember -Function Get-NewMyClass

Using it simply requires we import the module, then call the function. From there we can access the properties and methods of our function.

# Import our test module
Import-Module -Force 'C:\PS\Classes and Modules\mymodule.psm1'

# Use the function to generate a new instance of the 'MyClass' class
$myClassFunction = Get-NewMyClass

# Call a method from it

# Get a property of the class

Pretty simple and straightforward. This can be a useful method if there are extra checks you wish to do inside the module prior to returning the new instance of the class.

The next method simply has us create a variable within the module, and export that as a module member.

$newClass = [MyClass]::new()
Export-ModuleMember -Variable newClass

You’d then use it in your script, just like any other variable:

# The module also has a variable exported from the function
# of type MyClass. 

With that shown I have to say I really don’t like this method. Primarily it is due to the issue of name collisions. If you have a variable also named $newClass in your script, it will block out the one from the class causing the collison.

The final option is the new using clause. I want to give a shout out to PowerShell MVP Dave Wyatt (blog | twitter) for pointing this one out to me.

As the first line of your script (except for comments, which are allowed before it) you use the syntax “using module” followed the module name, or path to the module.

using module 'C:\PS\Classes and Modules\mymodule.psm1'

Here I hard coded the path to the module since this is a simple demo. If the module had been installed in one of the default locations for modules, such as the WindowsPowerShell\Modules folder in the current users Documents area, you could have omitted the path and just put the name of the module.

After this, you would simply create a new variable from the class and use it normally.

$myClassUsing = [MyClass]::new()

# Setting / Getting property
$myClassUsing.MyString                  # Show default property
$myClassUsing.MyString = 'ArcaneCode'   # Change the value
$myClassUsing.MyString                  # Show the change

# Calling a method

Note that if you had multiple modules you wanted to access the class definitions in, you would simply have multiple lines of “using module”, each line referencing the module you wanted.

using module 'C:\PS\Classes and Modules\mymodule.psm1'
using module 'C:\PS\Classes and Modules\anothermodule.psm1'


There you go. Three ways you can access a class definition stored inside a module, externally. Now not only can you create useful, reusable classes, you can also organize them into modules and use them outside the modules.

High Class PowerShell–Presenting for the SQL PASS PowerShell Virtual Chapter

I’m pleased to announce I’ll be presenting for the SQL PASS PowerShell Virtual Chapter this Wednesday April 6th, 2016, at 12 pm Eastern Time (GMT-5).

In this session I’ll focus on the ability to create custom objects in PowerShell, covering PowerShell versions 3 to 5. I’ll then dive into the use of the new Class and Enum types introduced in PowerShell 5.

To join me, simply go to and register. It’s free, fast and easy. If you can’t make it live, don’t worry these sessions are recorded and will be posted for viewing later.

Hope to see everyone there!

Getting Music on your Windows Phone with Windows Media Player

I admit it. I have a Windows Phone. And I like it.

I’ve had an iPod, which is more than enough to tell me I don’t want an iPhone. Every time I switched PCs it was like starting over with a brand new device. Egad.

I also had an Android phone. It did a terrible job of letting me organize my apps, and often rearranged them after an update, leaving me once again to try and find where the heck everything is.

No, I like the simplicity of my Windows Phone. Easy to use, easy to setup. True, as critics say there’s not a lot of apps. But an awful lot of what I need I can do just via the web. Starbucks is a great example, they have an excellent mobile website through which I can check my card balance, see my current points (stars), and easily refill my card.

Truth be told, I actually have two Windows Phones. One is my large Samsung ATIV-SE, which I use daily. I also have a small inexpensive Nokia, only has 4 gig of ram but takes a 128 gig SD card. (The SD card cost twice as much as the phone.) When I travel I don’t want to run down the battery on my Samsung phone, so it works as a great device for playing my music, podcasts, and Audible audiobooks. Additionally, f something ever happened to the Samsung I can run and get a cheap SIM card and use it for a backup. I’ve nick named it ‘Zune’.

The one painful thing is getting music on my phones. One option is to simply open up File Explorer and copy things across. But that doesn’t let you really manage it well, and doesn’t help with playlists.

Another option is the Windows Phone desktop app. What a big pile of steaming poo that is. There’s a Windows 8 style app for it, which isn’t any better but is prettier. Of course there’s Groove / XBox Music. It does a great job of organizing music and playlists. But wait, it doesn’t talk to the Windows Phone. WTF Microsoft??? Come on, three different apps, none of which are worth a flip with the Windows Phone.

I’ve found the best app to be good old Windows Media Player. Yes, you heard me, the ancient but venerable Windows Media Player. It is easy to organize music and other types of media, as well as create playlists. Even better, when I plug in my phones it just recognizes them and shows up in the Sync tab. All I have to do is drag playlists or other media to it and click the start sync, and away it goes.

Unfortunately it’s a one way sync, it won’t retrieve things from the phone, but I can live with that.

I did have one frustrating moment last night. I was creating some new playlists, then when I went to sync them something happened. Not sure what, but everything went kablooie. Sync failed, and when I looked back many of my playlists had vanished.

I uttered a long string of explicatives involving the fleas of a thousand llamas and the armpits of most Microsoft Executives, then sighed and went to recreate one of them. When I did, it told me the list already existed! I went to look and of course didn’t see it, but I still had some glimmer of hope my lists were still there, like gold nuggets waiting to be found.

I put my Bingfu skills to work, and quickly found this question/answer in the Microsoft forums:

The solution came from one Afzal Taher, who appears to be a Microsoft employee. Or at least he was as of 2010 when the answer was posted.

His answer had multiple options you could try, but the first was all I needed. (If the below doesn’t work for you reference the above link).

1. Exit Windows Media Player.

2. Hold down the Windows Key and press R (for Run). Type %LOCALAPPDATA%\Microsoft\Media Player and click OK.

3. Select all the files in that folder, and delete them. NOTE! DO NOT DELETE THE FOLDERS! Only the files.

4. Restart Windows Media Player.

Of course any time you delete files, do it with caution, and you’re on your own, no warranties from me.

When you restart Windows Media Player, it will begin rebuilding its database. I have literally hundreds of gigs of music. My collection has records and/or CDs back to the late 70’s that I’ve digitized because I’m really old and we all know the last decade for original music was the 80’s. Except for ZZ Top. No matter when their stuff comes out, it rocks. (Also a shout-out to DJ Lobsterdust for his really innovative mash-ups.)

Anyway, this was an overnight process for me. But this morning, all my songs and playlists were back, even the ones that had vanished. I was able to sync my playlists to my phones with no problem, and am now happily rocking out while writing some PowerShell code.

Hmmm. PowerShell + Windows Phone + Windows Media Player. I wonder….

Encoding Strings to Base64 in C# – The Movie

Way back in 2007 I wrote a blog post entitled “Encoding Strings to Base64 in C#”. This continues to be my #1 referenced post.

The guys over at Webucator have turned my post into an instructional video, and I couldn’t be happier with the results. You can find the video on YouTube at:

Make sure to give ‘em a like for all their hard work!

Easy Installation of Your Own PowerShell Modules

I’ve been working a lot with PowerShell of late, developing modules and deploying them to my own Modules folder. This is a pretty basic set of tasks, something I do over and over. As such, I decided to script it!

First thing I wanted to do was ensure the WindowsPowerShell\Modules folder exists under the users Documents folder. To do that I created a simple function, Add-WindowsPowerShellFolder. If the WindowsPowerShell folder, and under it the Modules folder, don’t exist, they are created.

# This checks to see if the WindowsPowerShell folder is in the users
# document folder, then checks to see if the Modules folder exists under
# the WindowsPowerShell folder. If they do not exist, they are created.
# This is primarily a helper function for the Install-MyModule function
function Add-WindowsPowerShellFolder()
  $psUserPath = "C:\Users\$([Environment]::UserName)\Documents\WindowsPowerShell"
  if($(Test-Path $psUserPath) -eq $false)
    New-Item -ItemType Directory -Force $psUserPath

  $psUserModulePath = "$($psUserPath)\Modules"
  if($(Test-Path $psUserModulePath) -eq $false)
    New-Item -ItemType Directory -Force $psUserModulePath


Next, I check to see if the folder for the specific Module I’m wishing to deploy exists, and if not create it.

# This checks to see if the folder for the Module you want to install
# exists, and if not it adds it.
# This is primarily a helper function for the Install-MyModule function
function Add-ModuleFolder($ModuleName)
  $psUserModulePath = "C:\Users\$([Environment]::UserName)\Documents\WindowsPowerShell\Modules"

  $psModulePath = "$($psUserModulePath)\$($moduleName)"
  if($(Test-Path $psModulePath) -eq $false)
    New-Item -ItemType Directory -Force $psModulePath


Finally I call the main function, the Install-MyModule. This has two parameters, the name of the Module and a collection of files to copy.

First, I use the functions above to validate the needed folders exist. There is also a switch, –Replace, which will delete all files and subfolders in the target module folder.

After this is a simple routine that loops over each file and copies it to the target. This allows you to copy files from multiple folders all to the same target.

This routine does assume there are no subfolders to be deployed to the target module folder, which is pretty common.


# This is the main function of this script. It first ensures the requisite
# folders exist in order to deploy.
# If the -Replace switch is used, the target folder will be cleaned out
# prior to the copy.
# Next, it iterates over the list of files passed in and copies them to the
# target folder.
function Install-MyModule()
  param ( 
         [Parameter( Mandatory = $true,
                     ValueFromPipeline = $false,
                     ValueFromPipelineByPropertyName = $false,
                     HelpMessage = ‘Module Name.’
         [string] $ModuleName,
         [Parameter( Mandatory = $true,
                     ValueFromPipeline = $false,
                     ValueFromPipelineByPropertyName = $false,
                     HelpMessage = ‘File to deploy.’
         [string[]] $Files,
         [switch] $Replace
        )  # End the parameter block

    # Validate the PS folder exists

    # Set the path to the users modules folder
    $psUserModulePath = "C:\Users\$([Environment]::UserName)\Documents\WindowsPowerShell\Modules"

    # Add a new folder for the module name being installed
    Add-ModuleFolder -ModuleName $ModuleName

    # Set the path to the users module folder including the module to create
    $psModulePath = "$($psUserModulePath)\$($ModuleName)"

    # If the user passed the -Replace switch delete all files from
    # the target folder
    if ($Replace -eq $true)
      Remove-Item "$psModulePath\*.*" -Force -Recurse


    foreach($file in $files)
      # Copy our module to the users module folder (force will overwrite if there)
      Copy-Item $file `
                $psModulePath `

Using it is straight forward. First, place the above code into a PS1, then execute it to load the functions into memory. You could also put it in your profile if it is something you do often.

In this example I’ve developed a module called ZipCodeLookup. This example installs it for me into my modules folder.

Install-MyModule ‘ZipCodeLookup’ ‘C:\PS\MyCode\ZipCodeLookup.*’ –Replace

Now you have a simple function you can call to deploy your modules, making your development life a little easier. It can also come in useful when sending a module to a coworker or setting up some common scripts on a different machine. It takes care of making sure the folders are in place as well as copying in your module.

Chattanooga SQL Saturday June 27 2015–Zero to Hero with PowerShell and SQL Server

This Saturday, June 27 2015, I will be at SQL Saturday #410 in Chattanooga, TN. I’ll be presenting a session “Zero to Hero with PowerShell and SQL Server”, in which we’ll start with the basics of PowerShell, then move into working with SQL Server via the PS SQL Provider.

This is going to be an extremely fast paced session, so you may wish to download the code samples ahead of time. I have already uploaded the samples to the event site. Just go to the Sessions menu, Schedule, and you’ll see a bit download button under the session. As of right now I’m the last session of the day, in room 219, but that is subject to change so be sure to check the schedule upon arrival.

Be warned, there is far more code in the download then we’ll be able to cover in a one hour session. It is well commented though, and you should be able to understand it after the session.

If you are looking for even more PowerShell goodness, my friend Aaron Nelson ( @sqlvariant | blog ) is doing a PowerShell for Data Professionals just after lunch. Our two sessions should work well together for those interested in using PowerShell in the world of SQL Server.

Hope to see you there!

SSRS 2012 Report Manager can’t load Microsoft.ReportingServices.SharePoint.ObjectModel

So I did it again, I broke my SQL Server. Well, sort of. I have a Hyper-V VM of Windows Server 2012R2 I use for development. On it I had SQL Server 2012 Developer Edition with all the latest service packs. I recently needed to do some work with 2014 as well, so installed SQL Server 2014 Developer Edition side by side. Everything seemed happy, until I opened up the SQL Server 2012 Report Manager webpage. It looked OK at first, but when I started clicking on things I started getting this error:

System.Configuration.ConfigurationErrorsException: Could not load file or assembly ‘Microsoft.ReportingServices.SharePoint.ObjectModel’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference

Icky. So a web search turned up one hit, a connect item filed by Brian Judge:

At the bottom, Brian gives the clue on how to fix the issue when he says:

If I change the redirect to stay on for the following policies then the problem appears to be resolved:






Alas, there are no specific instructions on just how to change the redirect. For those not familiar with the way these things work, I wanted to amplify his fix.

First, open a command window in administrator mode. I used the one that came with Visual Studio (the Developer Command Prompt for VS2012).

Next, change directory by using the “cd” command to the first item in the list above. (Click on the pic for a bigger image, should you have poor eyesight).


Using the DIR command, we can see one directory with a version number followed by what appears to be a hash value of some type. Issue another CD into that folder.


Using the DIR command again you will find two files in that folder:


Use notepad to edit the one with the .config extenstion.


When it appears, you will see something like:


Simply change the number in the newVersion from 12, to 11.


Repeat the steps for all four of the folders in the list above.

Next, and this is important kids, you need to stop and restart your SQL Server 2012 Reporting Services service, or simply reboot the computer. After that, your SSRS 2012 Report Manager should start to behave normally again. I’ve also tested the 2014 Report Manager, and it seems to work fine after the changes were applied. (In theory it shouldn’t have been affected, but you can never be too careful).

If you found this post useful, do us a favor. Go to the Microsoft Connect article linked at the top and give it an up vote, so Microsoft will begin to take notice. Also thanks again to Brian Judge (whom I do not know but hope to meet) for filing the original bug and giving the clue to fixing it.