Monthly Archive

Categories

Monthly Archives: August 2008

W2KSG: Making Decisions

Lets continue extending our PowerShell use and look at making decisions.  This corresponds to Listing 2.11 in the Scripting Guide -

Script Center Home > Microsoft Windows 2000 Scripting Guide > Scripting Concepts and Technologies for System Administration > VBScript Primer > VBScript Overview > Making Decisions Taking Multiple Actions by Using If Then Else

I'm skipping Listing 2.10 as is fully incorporated into 2.11.

We want to make some choices based on how much disk space is left.

## listing 2.11

cls

$convert = 1MB
$computer = "pcrs2"
$threshold = 100

$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk
foreach ($disk in $disks) {
    $free = [int]($disk.Freespace/$convert)
    if ($free -lt $threshold){
        Write-Host "$($disk.DeviceID) is low on diskspace"
    }
    else {
        Write-Host "$($disk.DeviceID) has adequate diskspace"
    }
}

New addition is a $threshold variable which is our limit in megabytes of acceptable free space.  We use WMI as before and loop through the collection. This time we compute the free space and compare if to the threshold value. Note the use of -lt for less than.  PowerShell comparison operators are -eq, -ne, -lt, -le, -gt, -ge NOT the =, !=, <, <=, >, >= that you might be used to. Expect to have to double check these when you start with PowerShell!

If the free space is less than the threshold value we print a warning otherwise (else) we print a message stating its OK.  For completeness Listing 2.10 is the same as this but without the else statement,

 

Share this post :

 

Technorati Tags: PowerShell

W2KSG: Mutiple Runs

We have a script that will run through the logical disks on a machine and return the free space.  How do we run that multiple times?

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

$convert = 1MB
$computer = "pcrs2"
#$pause = 3600     ## 1 hour
$pause = 10        ## 10 seconds

for ($i=1; $i -le 12; $i++){
## iterate through results collection
    $disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk

Get-Date -DisplayHint Time

    foreach ($disk in $disks) {
        Write-Host "There are $([int]($disk.Freespace/$convert)) megabytes of free disk space on $($disk.DeviceID)"
    }
    Start-Sleep -Seconds $pause
}

If we take our script from last time and warp it in another loop we can control how many times it runs.  In this case I've use a for loop with a counter that increments from 1-12. Within that loop we use get-date to display the time  and then display the free space.  PowerShell would run the loops continuously so we we use start-sleep to pause the script. For testing I used 10 seconds but you can choose any number of seconds - 3600 would be running it hourly.

It doesn't take a lot of PowerShell to give some very useful functionality.

 

Share this post :

 

Technorati Tags: Powershell

October PowerShell event

Don't forget there will be a TechNet PowerShell event in Birmingham (UK) on the afternoon of 14 October 2008.  Registration is open at http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032383908&Culture=en-GB

 

Share this post :

 

Technorati Tags: PowerShell

W2KSG: Using Collections

As we saw in the previous post Get-WMIObject returns a collection of objects. To continue with our script development to take that into account.

PowerShell handles objects on the pipeline so we don't need to use the collection explicitly

Listing 2.8 would become

## listing 2.8

$convert = 1MB
$computer = "pcrs2"

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

If you need to iterate through the results you would use foreach

Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk | ForEach-Object {

Write-Host "There are $([int]($_.Freespace/$convert)) megabytes of free disk space on $($_.DeviceID)"

}

Alternatively you could generate the collection and then iterate

## iterate through results collection
$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk

foreach ($disk in $disks) {

Write-Host "There are $([int]($disk.Freespace/$convert)) megabytes of free disk space on $($disk.DeviceID)"

}

This is closer to the VBScript approach and for very large collections may well be faster. The drawback to this approach is  is that you generate the objects and then work with them. Foreach-Object works on the pipeline as the objects appear.

If a collection is empty the Foreach-Object approach will just return nothing - not sure if it worked or not. To test if the results are empty use this

## test for empty collection
$tapes = Get-WmiObject -Class Win32_TapeDrive
if ($tapes -eq $null){Write-Host "No tape drives installed"}
else {    foreach ($tape in $tapes) {$tape.Name}}

We can't test for a collection with zero members as we do with VBScript so we have to test for the collection being null.

 

Share this post :

 

Technorati Tags: PowerShell

W2KSG: Concatenating Strings

We have seen how to use a string as a variable.  How do we join, or concatenate two strings.  The scripting guide has an example 

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

## listing 2.7

$convert = 1MB
$computer = "pcrs2"

Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter "DeviceId='C:'" | ForEach-Object {

"There are " + [int]($_.Freespace/$convert) + " megabytes of free disk space"
"There are $([int]($_.Freespace/$convert)) megabytes of free disk space"
}

We determine the free space as before.  This time we need to use a foreach-object to loop through the returned data.  We have only selected a single drive but it is still returned as a collection of objects rather than a single object.

If a string is defined on a line it is automatically written out. In the first example the strings are concatenated using the + symbol.  [int]($_.Freespace/$convert) is automatically turned into a string as integer to string is an allowed conversion.

In the second example we make use of PowerShell's ability to substitute values into a double quoted string. $([int]($_.Freespace/$convert))  tells PowerShell to treat everything between the outer() as a variable that will be substituted into the string.

Two ways of achieving the goal of embedding the value into the string. Use which ever you most comfortable with though the later is the more powerful.

 

Share this post :

 

Technorati Tags: PowerShell

W2KSG: Using Strings

We come to Listing 2.6 - using strings as variables

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

In this listing we add the ability to specify the computer  we are working with. WMI is great for remote administration and if you seen my recent posts PowerShell has fantastic WMI support

$convert = 1MB
$computer = "pcrs2"

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

Only addition is that we have defined a variable $computer to hold the computer name we want to interrogate.  In PowerShell we simply use with the -Computername parameter. Simple.

 

Share this post :

 

Technorati Tags: PowerShell

 

PowerShell in Sweden

September 16th brings a PowerShell event to Sweden.  In the morning I will be speaking on PowerShell in two sessions :

  • PowerShell Overview
  • Learning Powershell
  • Using WMI
  • Break
  • Administering Active Directory
  • Administering IIS 7

Registration for the event is here

http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032386415&Culture=sv-SE

In the afternoon there will be the first meeting of the Swedish\Nordic PowerShell User Group

All welcome.  If you are in the area please join us

 

Share this post :

 

Technorati Tags: PowerShell,Sweden

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

Windows 2000 Scripting Guide: Free Disk Space

The Windows 2000 Scripting Guide was an invaluable resource for VBScript users. It was one of the things that helped bring scripting into the mainstream of admin activity. It contains a lot of scripting background information but written from a VBScript viewpoint. The example scripts are still incredibly useful - but they are written in VBScript. From a PowerShell users view that doesn't help.  I am going to start working through the guide translating the scripts in to PowerShell.

The guide is available on line at http://www.microsoft.com/technet/scriptcenter/guide/default.mspx?mfr=true. Unfortunately the URL doesn't change as you navigate through the guide so I will have to supply navigation pointers as we go.

In the written book we will start at chapter 2 - online we are at

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

Listing 2.1 - Retrieving Free Disk Space

Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'" | Format-List Freespace

One line of PowerShell replaces 3 lines of VBScript. 

Use Get-WMIObject to pull back the Win32_LogicalDisk class. The -filter parameter can be used to control which disk - deviceid equates to drive letter in this case. Select the Freespace property as that's what we are interested in and use format-list to give a nice display.

It can be expanded to cover all disks by removing the filter

Get-WmiObject -Class Win32_LogicalDisk | Format-Table DeviceID, Freespace -AutoSize

We then add the deviceid to the selected properties and use format-table to display. Autosize will keep the columns from spreading all over the screen.

 

Share this post :

 

Technorati Tags: PowerShell

TechEd EMEA

Anyone interested in PowerShell and is going to be at TechEd EMEA (IT Pro) early in November - drop me a message if you want to meet up. Let me know especially if you are interested in the UK User group. There may well be other PowerShell related community stuff going on.  More later.

 

Share this post :

 

Technorati Tags: PowerShell,TechEd