Wednesday, November 29, 2006

Functions in PowerShell

Here is how to create a simple function in PowerShell. The function takes a single argument, and returns the twice the given amount. Note that the function works on both integers and strings (PowerShell handles multiplication of strings by repeating the string the given number of times).:

function MultiplyByTwo {
$temp = $args[0] * 2
Write-Output $temp
}

MultiplyByTwo 42

MultiplyByTwo "Bluebeard"

This is another example. The RetrieveData function calls two independent functions in order to retrieve the number of CPUs and the amount of memory of a given host:

function GetMem {
$temp = Get-WmiObject "Win32_LogicalMemoryConfiguration" -computername $args[0]
$MemInBytes = $temp.TotalPhysicalMemory * 1kb
Write-Output $MemInBytes
}

function GetNumCPU {
$temp = Get-WmiObject "Win32_ComputerSystem" -computername $args[0]
$nocpu = $temp.NumberOfProcessors
Write-Output $nocpu
}

function RetrieveData {
$tmpNoCPU = GetNumCPU $args[0]
$tmpMemInBytes = GetMem $args[0]
$computername = $args[0]
Write-Output "The Computer $computername has $tmpNoCPU CPU(s) and $tmpMemInBytes bytes of RAM installed."
}

RetrieveData "localhost"

No comments: