Beginning Powershell

When writing my first powershell script to check free disk space on a dozen exchange servers I picked up a few useful things for future reference.

  1. Echoing output to the command line
    A script can print/write output to stdout using Write-Host “Hello World” but this command is aliased too, so that echo “Hello World” will also work (as will write “Hello World”).
  2. Active Directory Cmdlets
    Install some cmdlets to make life easier when accessing AD from powershell: http://www.nsoftware.com/powershell/download.aspx
  3. Scheduled Tasks
    Adding a powershell script as a scheduled task (cron job) can be done from Start > Control Panel > Scheduled Tasks and the format for the command should be like this:
    C:\Windows\system32\windowspowershell\powershell.exe “& ‘c:\scripts\Get-ScriptName.ps1′”
    The parameter is surrounded by double-quotes “
    The path to the script is surrounded by single-quotes ‘
  4. Emailing a Format Table
    Assigning a format table to a variable and then trying to email that variable does not work without doing the following:
    $myVar = Get-Whatever | ft -auto | out-string

So that is what I have picked up and my first script to check disk usage on servers is here:

# Get-ExchangeDiskUsage.ps1
# Use Get-WMIObject to collect disk free info from a list of servers

$arrServers = (
“server1.ac.uk”,
“server2.ac.uk”,
“server3.ac.uk”
)

# If there is less than 5% free space an email alert will be sent
$intThresholdFreeSpace = 5.0

$SmtpServer = “smtp.ac.uk”

$From = “Whoever <whoever@ac.uk>”
$To = “alertme1@ac.uk”
$Cc = “alertme2@ac.uk”

function SendMailAlert {
$SmtpClient = New-Object Net.Mail.SmtpClient -arg “$SmtpServer”
$Message = New-Object Net.Mail.MailMessage($From,$To,”Exchange Alert: Low Disk Space”,$args[0])
$Message.cc.add($Cc)
$SmtpClient.send($Message)
#$SmtpClient.Send($From,$To,”Exchange Alert: Low Disk Space”,$args[0])
}

$volumename = @{ l = “Label”; e = “volumename”; f = “{0:-20}” }
$size = @{ l = “Size (GB)”; e = { $_.size/1gb}; f = “{0:N}”}
$free = @{ l = “Free (GB)”; e = { $_.freespace/1gb}; f = “{0:N}”}
$perc = @{ l = “Free (%)”; e = { 100.0 * ([double]$_.freespace/[double]$_.size)}; f=”{0:f}” }
$name = @{ l = “Drive”; e = “name”; f = “{0,-20}” }

$filter = “DriveType = ‘3’”
if ( $all ) { $filter = “” }

foreach($computer in $arrServers){
$fields = $name,$volumename,$size,$free,$perc
$EmailBody = get-wmiobject -class win32_logicaldisk -filter $filter -comp $computer | where { (100.0 * ([double]$_.freespace/[double]$_.size)) -lt $intThresholdFreeSpace -and (100.0 * ([double]$_.freespace/[double]$_.size)) -gt -1.0 } | ft $fields -auto | out-string
if($EmailBody -ne “”){
$EmailBody = $computer + $EmailBody
SendMailAlert $EmailBody
}
}

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>