Monthly Archive

Categories

W2KSG: Variables and Constants

The Scripting Guide uses the script we saw in the previous post - http://richardsiddaway.spaces.live.com/blog/cns!43CFA46A74CF3E96!1646.entry and uses variables and constants to calculate the free space in MB rather than bytes (Listing 2.3)

Script Center Home > Microsoft Windows 2000 Scripting Guide > Scripting Concepts and Technologies for System Administration > VBScript Primer > VBScript Overview Variables

PowerShell has a built in constant for MB - MB so we can change the scripts we saw previously to

Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'" | Format-List @{Label="FreeSpace(MB)";Expression={$_.FreeSpace/1MB}}

Get-WmiObject -Class Win32_LogicalDisk | Format-Table DeviceID, @{Label="FreeSpace(MB)";Expression={$_.Freespace/1MB}} -AutoSize

I both cases we create a calculated field using a specialised hash table. The Label becomes the column (or field) name and the expression is the calculation we apply. In this case Freespace divided by 1 megabyte so the result is returned as megabytes. $_ signifies the object coming down the pipeline.

If we wanted to duplicate Listing 2.4 and round to integer values we can do this

Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'" | Format-List @{Label="FreeSpace(MB)";Expression={[int]($_.FreeSpace/1MB)}}

Get-WmiObject -Class Win32_LogicalDisk | Format-Table DeviceID, @{Label="FreeSpace(MB)";Expression={[int]($_.Freespace/1MB)}} -AutoSize

by casting the calculated expression to an integer.

Finally we can duplicate Listing 2.5 by using a variable in the calculation.  In this case it doesn't help us much and adds another step to the code. The technique may be useful later

$convert = 1MB

Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'" | Format-List @{Label="FreeSpace(MB)";Expression={[int]($_.FreeSpace/$convert)}}

Get-WmiObject -Class Win32_LogicalDisk | Format-Table DeviceID, @{Label="FreeSpace(MB)";Expression={[int]($_.Freespace/$convert)}} -AutoSize

In this case we set a variable designated by $convert (all PowerShell variables start with $) to 1MB and use it as shown

 

Share this post :

Technorati Tags: PowerShell

Leave a Reply