Friday, 5 April 2013

Stopping a process with Powershell and the Out-GridView

Powershell can display a nice menu where the user can select e.g. a single or a multiple element in an arbitrary gridview, with the cmdlet Out-GridView. Let's see how this can be done to support stopping a single process of which the user chooses to stop. Of course, this is already available in Task Manager, but it is always nice to see that Powershell can give us a dedicated way of doing this also.

Here is the script for doing this, in the function Stop-SelectedProcess:

            
function Stop-SelectedProcess(){            
            
    Write-Host Select the process to stop ...            
    Start-Sleep 2            
                
    $selectedProcess = $null             
    Get-Process | Out-GridView -OutputMode Single -Outvariable selectedProcess            
                
    if ($selectedProcess -eq $null -or $selectedProcess.Count -eq 0)             
    {            
        return;            
    }             
            
    Stop-Process $selectedProcess            
            
}            
            
Stop-SelectedProcess
Make note how the Out-GridView cmdlet which we pipe the result from Get-Process to is specified to have an -OutputMode of single (i.e. choose one item at a time)and a -OutVariable also set, also note the missing $-sign after -OutVariable, this is correct. This shows how we can present the user with a nice menu to choose for while running the command. This is easier than asking the user to select a process to stop by e.g. PID or #-line number.

This is just another example of how modern as a scripting language Powershell really is.

Word of caution at the end - never stop a process you are not sure of what runs. I stopped the process smss process the other day, because I thought it was Sql Management Studio. Needless to say, I experienced my first BSOD in Windows 8 ..

Screenshot of the action:

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().