Thursday 4 April 2013

Dynamic modules in Powershell as objects

This article will show how dynamic modules can act as objects for Powershell. With this technique, it is possible to create object definitions in Powershell if you want more object orientation for your scripts. Let's first look at the Manifest file for the dynamic module. The file modasobj.psd1 contains the following:

#Module manifest for module 'modasobj            
#Generated by: Tore Aurstad            
            
@{            
ModuleVersion = '1.0'            
Guid = 'C9B7488B-507C-470C-B93E-6B040A5EF2AC'            
Author='Tore Aurstad'            
Description='Demonstrates use of modules as objects'            
            
ScriptsToProcess = @('modasobj.ps1')            
            
}
The manifest file will always have the name MODULENAME.psd1, where MODULENAME is the folder name under one of your $env:psmodulepath folders. As we see, we define the Guid, Author, Description and ModuleVersion. For non-dynamic modules, we specify more properties in the hashtable of our manifest .psd1 file for our Powershell modules. An overview of the manifest properties to set is here:

How to write a module manifest
We define our module as objects definitions in the other file, modasobj.ps1
function New-Address {            
            
 New-Module -AsCustomObject -Name Address {            
    $House = $null            
    $Street = $null            
    $Town = $null            
    $County = $null            
    $Country = $null            
    $PostCode = $null             
            
    Export-ModuleMember -Variable *            
            
 }            
            
}            
            
function New-Person {            
 New-Module -AsCustomObject -Name Person {            
    $Name = $null            
    $Address = $null            
    $Occupation = $null             
    $Age = $null            
    $NiNo = $null              
            
    Export-ModuleMember -Variable *            
            
  }            
            
}
Here we see the use of New-Module cmdlet, followed by the flag -AsCustomObject and the -Name flag followed by the name of the custom object we want to create. To play around with this object, we can just create a new Person object and set its address to be an Address object. Some output of this follows.


PS C:\users> import-module modasobj -verbose -force
VERBOSE: Loading module from path 'C:\Users\Tore Aurstad\Documents\WindowsPowerShell\Modules\modasobj\modasobj.psd1'.
VERBOSE: Loading module from path 'C:\Users\Tore Aurstad\Documents\WindowsPowerShell\Modules\modasobj\modasobj.ps1'.
VERBOSE: Dot-sourcing the script file 'C:\Users\Tore
Aurstad\Documents\WindowsPowerShell\Modules\modasobj\modasobj.ps1'.
PS C:\users> $me = New-Person
PS C:\users> $me


Address    :
Age        :
Name       :
NiNo       :
Occupation :

PS C:\users> $me.Age = 34
PS C:\users> $me.Name = 'Tore Aurstad'
PS C:\users> $me.Occupation = 'System Developer'
PS C:\users> $me.Occupation = 'Systems Developer'
PS C:\users> $me.Address = 'Kyavegen 1 7045 Trondheim'
PS C:\users> $me.Address.Country = 'Norway'
Property 'Country' cannot be found on this object; make sure it exists and is settable.
At line:1 char:1
+ $me.Address.Country = 'Norway'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

PS C:\users> $me.Address.County = 'Sør-Trøndelag'
Property 'County' cannot be found on this object; make sure it exists and is settable.
At line:1 char:1
+ $me.Address.County = 'Sør-Trøndelag'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

PS C:\users> $address = New-Address
PS C:\users> $me.Address = $address
PS C:\users> $address.Country = 'Norway'
PS C:\users> $me


Address    : @{Country=Norway; County=; House=; PostCode=; Street=; Town=}
Age        : 34
Name       : Tore Aurstad
NiNo       :
Occupation : Systems Developer

PS C:\users> $address.County = 'Sør-Trøndelag'
PS C:\users> $address.House = '1'
PS C:\users> $address.PostCode = '7045'
PS C:\users> $address.Street = 'Kyavegen'
PS C:\users> $address.Town = 'Trondheim'
PS C:\users> $me

Address    : @{Country=Norway; County=Sør-Trøndelag; House=1; PostCode=7045; Street=Kyavegen; Town=Trondheim}
Age        : 34
Name       : Tore Aurstad
NiNo       :
Occupation : Systems Developer

PS C:\users>

PS C:\users> $me.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PSCustomObject                           System.Object


PS C:\users> $address.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PSCustomObject                           System.Object


PS C:\users> $me | Get-Member


   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Address     NoteProperty System.Management.Automation.PSCustomObject Address=@{Country=Norway; County=Sør-Trøndelag...
Age         NoteProperty System.Int32 Age=34
Name        NoteProperty System.String Name=Tore Aurstad
NiNo        NoteProperty  NiNo=null
Occupation  NoteProperty System.String Occupation=Systems Developer


PS C:\users>

As you can see, I had to adjust above the way I was setting $me.Address properties by having to declare a new address object $address and set its properties to see the changes reflected in the parent object $me. Both objects are of type PSCustomObject. As we can see, when we pipe our object variable to the cmdlet Get-Member, we get a nice listing of our members and derived members. This shows how custom objects can be made inline in Powershell. Of course, Powershell can create objects easily with the New-Object cmdlet and by specifying a library object either in .NET or created by you, but this shows how you don't have to recompile and create an object specification or class, you can have Powershell create for you, with dynamic modules and the -AsCustomObject and -Name flags set inside the function. In addition, you need to use the cmdlet Export-ModuleMember-Property *, such that your properties are visible for consumers of the dynamic module.

If you want to remove the module again, use:
remove-module modasobj*

Modules are a huge topic and this article shows one of their many ways of being created.

Using Powershell to generate new Guids

Guids, or Globally Unique Identifiers, are often used by developers and others to attribute a unique id to an arbitrary object. For example, those who have used WiX to create MSI-based installers, often need to create a new GUID all the time while writing the WiX code for the installer. Wouldn't it be great to use a Powershell command line to just generate new GUIDs? Here is a sample script how to do this:

            
<#
    .SYNOPSIS
        Creates a new Guid object and displays its GUI to the screen
    .DESCRIPTION
        Uses static System.Guid.NewGuid() method to create a new Guid object
    .EXAMPLE
        1. Create a new Guid is easy:
        New-Guid
#>            
function New-Guid () {            
            
 [System.Guid] $guidObject = [System.Guid]::NewGuid()            
 [Windows.Forms.Clipboard]::Clear();            
 [Windows.Forms.Clipboard]::SetText($guidObject.Guid)            
 Write-Host $guidObject.Guid            
            
}            
            
New-Guid


To call the function New-Guid just type its name. You will get new GUIDs without a hassle:


PS C:\users\Tore Aurstad> New-Guid
0d2cc38f-e6de-4049-ae6a-f168bf1ea670

PS C:\users\Tore Aurstad> New-Guid
f99044b3-a8a6-4092-a520-c58ae259a19e

PS C:\users\Tore Aurstad> New-Guid
4de11003-8bbf-4415-8fe3-e7ecf4be9ee0

PS C:\users\Tore Aurstad> New-Guid
cac473e7-1f01-4d2f-b99c-4fdb25ab9da1

PS C:\users\Tore Aurstad> 



Of course, this is very similar to creating a Console application with C#, we just call the static method NewGuid on the Guid class. In Powershell, variables can be strongly typed as shown here and to call a static method you just write [MyNamespace.MyClass]::MyStaticMethod. Note the double colon marks in the middle.

In addition to generating a new Guid, the clipboard contents is set to the Guid value, which means you can paste in the text where you want. I did not have to import any additional modules to reach the static function [Windows.Forms.Clipboard]::Clear() and [Windows.Forms.Clipboard]::SetText().

Performing backups of a database with Powershell

This article will show some Powershell script to perform a backup of a database with Powershell. Generating backups of a database is not that hard with Powershell. A backup is done by using the Server Management Objects or SMO. This is an individual download that can be downloaded for SQL Server 2008 (R2) or SQL Server 2012. I have used SQL Server 2012 Express, and this script also runs with the Express version of SQL Server 2012. I had to download additional packages for SQL from here:

Microsoft SQL Server 2012 SP1 Feature Pack

Obtain the SharedManagementObjects MSI-file and the PowershellTools MSI file, I downloaded the x64 version, but if you have x86 version of SQL Server 2012, use that instead. In addition, there are equivalent packages for Microsoft SQL Server 2008 (R2), Google is your friend here.. Here is the script to perform a backup. I have created a function or cmdlet called Backup-Database. There is also a function called PreLoad-SmoAssemblies, which I have not used, but this can be used to PreLoad the entire SMO Library if you want an example of how to do this.

            
function PreLoad-SmoAssemblies(){            
 $smoAssemblies = "Microsoft.SqlServer.Management.Common",            
"Microsoft.SqlServer.Smo",            
"Microsoft.SqlServer.Dmf ",            
"Microsoft.SqlServer.Instapi ",            
"Microsoft.SqlServer.SqlWmiManagement ",            
"Microsoft.SqlServer.ConnectionInfo ",            
"Microsoft.SqlServer.SmoExtended ",            
"Microsoft.SqlServer.SqlTDiagM ",            
"Microsoft.SqlServer.SString ",            
"Microsoft.SqlServer.Management.RegisteredServers ",            
"Microsoft.SqlServer.Management.Sdk.Sfc ",            
"Microsoft.SqlServer.SqlEnum ",            
"Microsoft.SqlServer.RegSvrEnum ",            
"Microsoft.SqlServer.WmiEnum ",            
"Microsoft.SqlServer.ServiceBrokerEnum ",            
"Microsoft.SqlServer.ConnectionInfoExtended ",            
"Microsoft.SqlServer.Management.Collector ",            
"Microsoft.SqlServer.Management.CollectorEnum",            
"Microsoft.SqlServer.Management.Dac",            
"Microsoft.SqlServer.Management.DacEnum",            
"Microsoft.SqlServer.Management.Utility";            
             
 foreach ($assembly in $smoAssemblies){            
  [void][System.Reflection.Assembly]::LoadWithPartialName($assembly);               
 }            
            
}            
            
            
function Backup-Database($dbinstance, $dbname, $saveToLocation = "C:\backups\")            
{            
             
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null            
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null            
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null             
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null             
            
 $dbserver = New-Object Microsoft.SqlServer.Management.Smo.Server $dbinstance            
 $bkup = New-Object Microsoft.SqlServer.Management.Smo.Backup             
 $bkup.Database = $dbname            
            
 $date = Get-Date             
 $date = $date -replace "\.", "-"             
 $date = $date -replace ":", "-"             
 $date = $date -replace " ", "-"             
            
 $file = $saveToLocation + $dbname + "_" + $date + ".bak"            
            
 $bkup.Devices.AddDevice($file, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)             
 $bkup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database             
            
 $bkup.SqlBackup($dbinstance)            
            
 Write-Host "Backup of database $database performed at $(Get-Date) to file location $saveToLocation"            
            
 trap [Exception]             
 {            
  Write-Host $_.Exception.Message            
  break            
 }            
            
}            
            
$dbinstanceToUse = $env:COMPUTERNAME + "\SQLEXPRESS"            
$dbnameToUse = "TestDatabase"             
            
Backup-Database $dbinstanceToUse $dbnameToUse             
The function or cmdlet Backup-Database takes three parameters. The $dbinstance is the computer name - db instance name to use for the $dbserver inside the function. The $dbname is the name of the database, while $saveToLocation is the location where to save the .bak backup file. Each .bak file will get a name of $dbname concatenated with a date stamp with the .bak extension in the end of the file name. The file location can be specified, but will default to c:\backups. Obviously, you want to either specify this or make sure that the location c:\backup exists first. The script can be adjusted by using Test-Path to make sure that the folder exists first.

This shows how Powershell can be used for a wide variety of tasks, such as performing a backup of a SQL server database.