Monday, May 11, 2015

Using Powershell to email free space

Below are two script


Put the following into a PowerShell file (EmailFreeSpace.ps1) and execute.

Clear-Host
$Body = Get-WmiObject Win32_logicaldisk -ComputerName LocalHost `
| Format-Table DeviceID, MediaType, `
@{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
@{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
@{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
-AutoSize


$EmailFrom = "test@gmail.com"
$EmailTo = "test@gmail.com"
$Subject = "Notification from XYZ"  

$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("test@gmail.com", "password here");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)


The output of the first part of the script will look like this:

DeviceID MediaType Size(GB) Free Space(GB) Free (%)
-------- --------- -------- -------------- --------
C:              12      232            174   75 %
D:              12      233            155   67 %
H:               0     7500           5634   75 %
J:               0      100            100  100 %
K:              11        0              0
Q:              12        0              0


The second part of the script will send an email using Gmail. You need to have a Gmail account and you will need to put the password on the second to last line of the script. You can also use any other STMP server such as Hotmail, etc.

No comments: