Thursday, April 16, 2009

Creating Functions in PowerShell

I have told you before in my previous blogs about Hyper-V and PowerShell to play with VHDs using WMI

This requires that every time we need to get VHD info we have to write  the below

$computer = "LocalHost"
$namespace = "root\virtualization"
$disk=Get-WmiObject -class Msvm_ImageManagementService -computername $computer -namespace $namespace

then we have to remember the method name or use get-member commandlet then we can use it like below:

$disk.GetVirtualHardDiskInfo(“c:\vhds\sccom.vhd”)

What I will add today that we can create something like command-let; this is so called functions in PowerShell

It is very easy just type the function name followed by open brackets { then   type your commands in one or more lines then close it by }

Lets create function to give us VHD disk info and lets name it get-diskinfo

function get-diskinfo {
$computer = "LocalHost"
$namespace = "root\virtualization"
$disk=Get-WmiObject -class Msvm_ImageManagementService -computername $computer -namespace $namespace
$disk.GetVirtualHardDiskInfo(“c:\vhds\scom.vhd”)
}

then you just execute the function name like get-diskinfo then it will work seamlessly

image

the problem that we will execute it and every time it will execute against the same disk

we need to use variables or we can name it parameters.

There are variables called $args[0] or $args[1] or $args[2] and so one; these can be used to get parameters when you execute the command so $args[0] is the first parameter then $args[1] is the second parameter and so on.

Then we will add $args[0] after the $disk.GetVirtualHardDiskInfo( like $disk.GetVirtualHardDiskInfo($args[0])

function get-diskinfo {
$computer = "LocalHost"
$namespace = "root\virtualization"
$disk=Get-WmiObject -class Msvm_ImageManagementService -computername $computer -namespace $namespace
$disk.GetVirtualHardDiskInfo($args[0])
}

so we can now type 

get-diskinfo “c:\vhds\scom.vhd”

the final question running into my head; when we close the PowerShell console this function will remain or it will disappear

actually it will disappear so we have to load it everytime the console starts

to do so we have something called profile script which automatically starts every time you run the PowerShell console

to access the your console profile script you can type

notepad $profile

it will open the profile in the notepad almost it will give you error as the file is not created yet

so you can use command like

fsutil file createnew $profile 1

This will create file on this path %Userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Now, you can edit it and add your functions so you can use it everytime you lunch the PowerShell Console.

image

Thank you for reading and I hope this was usefull.