How to send email from a VBS file.

Local Email Server

This is the standard method. It assumes an SMTP email server is installed on your machine. This is the case on most web servers.

 Set objMessage = CreateObject("CDO.Message") 
 objMessage.Subject = "Subject"
 objMessage.Sender = "[email protected]"
 objMessage.To = "[email protected]"
 objMessage.TextBody = "iMacros script completed. Status = OK"
 objMessage.Send

Substitute your own email information and message text. You can insert this code into any script that requires a message to be sent.

Remote Email Server

This code shows you how to use a remotes server rather than the SMTP server on your own machine.

 Set objMessage = CreateObject("CDO.Message") 
 objMessage.Subject = "iMacros Message" 
 objMessage.From = "[email protected]" 
 objMessage.To = "[email protected]" 
 objMessage.TextBody = "iMacros script completed. Status = OK

 '==This section provides the configuration information for the remote SMTP server.
 '==Normally you will only change the server name or IP.
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 
 'Name or IP of Remote SMTP Server
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.myserver.com"
 'Server port (typically 25)
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25  
 objMessage.Configuration.Fields.Update
 '==End remote SMTP server configuration section==

 objMessage.Send

Remote Email Server with Password

Sending a text email using authentication against a remote SMTP server. More and more administrators are restricting access to their servers to control spam or limit which users may utilize the server. This example shows you how to use basic authentication, the most commonly used authentication method, when the SMTP server you are using requires it.

This code is slightly more complex but not very difficult to understand or work with.

 Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory. 
 Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network). 

 Const cdoAnonymous = 0 'Do not authenticate
 Const cdoBasic = 1 'basic (clear-text) authentication
 Const cdoNTLM = 2 'NTLM

 Set objMessage = CreateObject("CDO.Message") 
 objMessage.Subject = "iMacros Status Message" 
 objMessage.From = """iMacros"" " 
 objMessage.To = "[email protected]" 
 objMessage.TextBody = "iMacros script completed. Status = OK"

 '==This section provides the configuration information for the remote SMTP server.

 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 

 'Name or IP of Remote SMTP Server
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.your.com"

 'Type of authentication, NONE, Basic (Base64 encoded), NTLM
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic

 'Your UserID on the SMTP server
 objMessage.Configuration.Fields.Item _
  ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "youruserid"

 'Your password on the SMTP server
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "yourpassword"

 'Server port (typically 25)
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

 'Use SSL for the connection (False or True)
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False

 'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP   server)
 objMessage.Configuration.Fields.Item _
 ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

 objMessage.Configuration.Fields.Update

 '==End remote SMTP server configuration section==  

 objMessage.Send

Send email with MAPI

This solution assumes that Outlook or another email client with MAPI support is installed.

 Dim ToAddress
 Dim MessageSubject
 Dim MessageBody
 Dim MessageAttachment

 Dim ol, ns, newMail

 ToAddress = "Jim, Test"   ' change this...
 MessageSubject = "iMacros"
 MessageBody = "iMacros Status = OK"

 Set ol = WScript.CreateObject("Outlook.Application")
 Set ns = ol.getNamespace("MAPI")
 ns.logon "","",true,false
 Set newMail = ol.CreateItem(olMailItem)
 newMail.Subject = MessageSubject
 newMail.Body = MessageBody & vbCrLf

 ' validate the recipient, just in case...
 Set myRecipient = ns.CreateRecipient(ToAddress)
 myRecipient.Resolve
 If Not myRecipient.Resolved Then
 MsgBox "unknown recipient"
 Else
    newMail.Recipients.Add(myRecipient)
    newMail.Send
 End If

 Set ol = Nothing

Source: http://wiki.imacros.net/send-email.vbs

VBS – Check Folder/File size

Below is an example off a VBS script to monitor the size of a directory or a file. If the size is larger then the size specified it will mail a message with a warning.

Script to monitor a folder:

strFolderToMonitor = "C:\TEST"
intSizeInGB = 12
intSizeInBytes  = (intSizeInGB * 1024 * 1024 * 1024)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolderToMonitor) 

If objFolder.Size > intSizeInBytes Then
  Set objMessage = CreateObject("CDO.Message")
  objMessage.From = "[email protected]"
  objMessage.To = "[email protected]"
  objMessage.Subject = "Folder " & strFolderToMonitor & " exceeded " & intSizeInGB & "GB"
  objMessage.TextBody = "The folder " & strFolderToMonitor & " has exceeded " & intSizeInGB & "GB.  Please panic in an orderly fashion." 

  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.domain.suffix"
  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
  objMessage.Configuration.Fields.Update 

  objMessage.Send
End If

 

Script to monitor a file:

strFileToMonitor = "C:\TEST\TEST.TXT"
intSizeInGB = 30
intSizeInBytes  = (intSizeInGB * 1024 * 1024 * 1024)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strFileToMonitor)

'If objFolder.Size > intSizeInBytes Then
If objFile.Size > intSizeInBytes Then
  Set objMessage = CreateObject("CDO.Message")
  objMessage.From = "[email protected]"
  objMessage.To = "[email protected]"
  objMessage.Subject = "File " & strFileToMonitor & " exceeded " & intSizeInGB & "GB"
  objMessage.TextBody = "The file " & strFileToMonitor & " has exceeded " & intSizeInGB & "GB." & chr(10) & chr(13) & "Please panic in an orderly fashion." 

  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.domain.suffix"
  objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
  objMessage.Configuration.Fields.Update 

  objMessage.Send
End If

 

Or download the files here:

[wpdm_file id=”19″]

[wpdm_file id=”20″]

MsSQL: Database in restoring state

When a MsSQL database has a mirror and something goes wrong, the database can end up in a restoring state. To force a recover of the database use the following command:

  • restore database <database> with recovery

This will make the database go on line.

To delete the database, use the following command:

  • drop database <db>

This command will remove the database and database files.

MsSQL: Move tempdb

When you need to move a database in MsSQL -in this case the tempdb- you can use two scripts:

use tempdb
go
sp_helpfile
go

 

When running this script, it will show the location of the tempdb database

This script is usefull to determine the file location of the databases. After relocating the database, these files can be removed.

With the following script, you can move the tempdb database to another location:

use master
go
Alter database tempdb modify file (name = tempdev, filename = 'E:\MSSQL\DATA\tempdb.mdf')
go
Alter database tempdb modify file (name = templog, filename = 'F:\MSSQL\DATA\templog.ldf')
go

After this script is run, the SQL services need to be restarted and the old files can be removed.

VB Script: DiskSpace Monitoring

When i needed a script to check multiple servers for disk usage, i found this script: http://gallery.technet.microsoft.com/ScriptCenter/en-us/cc8176ab-348b-4152-b9a3-25b6ad950d3e

Download it here: [wpdm_file id=”17″], or see the code:

'******************************************************************************
'* Provides data from disks from a list of servers (servers.txt)              *
'* Created by Nag Pal and Modify by Martin Scaine                             *
'* The original script don't manage error,                                    *
'* so if you can't connect to a server it will repeat the data from last.     *
'* Also I include the date on the name of the report file and on it header.   *
'* It can be usefull if you need to check it every day                        *
'******************************************************************************

On Error Resume Next
Const ForAppending = 8
Const HARD_DISK = 3
Const ForReading = 1

'Var declaration
dtmDay = Day(Date)
dtmMonth = Month(Date)
dtmYear = Year(Date)
dtmDate = CDate(dtmYear & "-" & dtmMonth & "-" & dtmDay)

Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the server list
Set SrvList = objFSO.OpenTextFile("Servers.txt", ForReading)

'Create a result file
If dtmday < 10 and dtmMonth >9 then
Set ReportFile = objFSO.OpenTextFile ("Srv_Disk_Space_" & dtmYear & "-" & dtmMonth & "-0" & dtmDay & ".html", ForAppending, True)
End If
If dtmday > 9 and dtmMonth < 10 then
Set ReportFile = objFSO.OpenTextFile ("Srv_Disk_Space_" & dtmYear & "-0" & dtmMonth & "-" & dtmDay & ".html", ForAppending, True)
End If
If dtmday < 10 and dtmMonth < 10 then Set ReportFile = objFSO.OpenTextFile ("Srv_Disk_Space_" & dtmYear & "-0" & dtmMonth & "-0" & dtmDay & ".html", ForAppending, True) End If If dtmday > 9 and dtmMonth >9 then
Set ReportFile = objFSO.OpenTextFile ("Srv_Disk_Space_" & dtmYear & "-" & dtmMonth & "-" & dtmDay & ".html", ForAppending, True)
End If
i = 0

'Inicializar HTML
ReportFile.writeline("")
ReportFile.writeline("")
ReportFile.writeline("")
ReportFile.writeline("")
ReportFile.writeline("")
ReportFile.writeline("
-->")
ReportFile.writeline("")
ReportFile.writeline("")

ReportFile.writeline("

“) ReportFile.writeline(“”) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(”

“) ReportFile.writeline(“Server Space Disk Report ” & dtmdate & ““) ReportFile.writeline(“
")

'Server name declaration
Do Until SrvList.AtEndOfStream
	StrComputer = SrvList.Readline

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")

	If Err.Number <> 0 Then
		ReportFile.writeline("

“) ReportFile.writeline(“”) ReportFile.writeline(” “) ReportFile.writeline(” “) Err.Clear Else ReportFile.writeline(”

Error – ” & StrComputer & ” – Error

“) ReportFile.writeline(“”) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(“”) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(” “) ‘Data recolection For Each objDisk in colDisks ‘Var init TotSpace=0 FrSpace=0 FrPercent=0 UsSpace=0 Drv=”Error” VolName=”Error” ‘Var charge TotSpace=Round(((objDisk.Size)/1073741824),2) FrSpace=Round(objDisk.FreeSpace/1073741824,2) FrPercent=Round((FrSpace / TotSpace)*100,0) UsSpace=Round((TotSpace – FrSpace),2) Drv=objDisk.DeviceID VolName=objDisk.DeviceID ‘Lnt=Len(VolName) ‘If Len(VolName) = 3 then If FrPercent > 20 Then ReportFile.WriteLine ” ” ElseIf FrPercent < 10 Then ReportFile.WriteLine ” ” Else ReportFile.WriteLine ” ” End If ‘Else ‘End If Next End If ReportFile.writeline(“”) ReportFile.writeline(” “) ReportFile.writeline(” “) ReportFile.writeline(”

” & StrComputer & “
Drive / Mount Total Capacity (in GB) Used Capacity (in GB) Free Space (in GB) Freespace %
” & Drv & “ ” & TotSpace & “ ” & UsSpace & “ ” & FrSpace & “ ” & FrPercent & “%” &”
” & Drv & “ ” & TotSpace & “ ” & UsSpace & “ ” & FrSpace & “ ” & FrPercent & “%” &”
” & Drv & “ ” & TotSpace & “ ” & UsSpace & “ ” & FrSpace & “ ” & FrPercent & “%” &”
")
Loop
ReportFile.WriteLine ""

How to backup a MsSQL database to a Share

 Use a MsSQL query to backup a database to a network share:

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE

exec master.dbo.xp_cmdshell 'net use Z: \\sharename password /user:user'
BACKUP DATABASE Staging TO DISK='Z:\database.bak'
EXEC master.dbo.xp_cmdshell 'net use /delete Z:'

EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE
EXEC master.dbo.sp_configure 'show advanced options', 0
RECONFIGURE

PowerCLI: Windows Disk Alignment on VMware

Searching for disk alignments off the windows 2003 servers on VMware ESX i found a CLI script which can automate the search. The original site: http://ict-freak.nl/2009/12/15/powercli-check-partition-alignment-windows-vms-only/

Script:

$myCol = @()
$vms = get-vm | where {$_.PowerState -eq "PoweredOn" -and `
$_.Guest.OSFullName -match "Microsoft Windows*" } | Sort Name 

foreach($vm in $vms){
$wmi = get-wmiobject -class "Win32_DiskPartition" `
-namespace "root\CIMV2" -ComputerName $vm            

    foreach ($objItem in $wmi){
        $Details = "" | Select-Object VMName, Partition, Status
            if ($objItem.StartingOffset -eq "65536"){
                $Details.VMName = $objItem.SystemName
                   $Details.Partition = $objItem.Name
                $Details.Status = "Partition aligned"
            }
            else{
                $Details.VMName = $objItem.SystemName
                   $Details.Partition = $objItem.Name
                $Details.Status = "Partition NOT aligned"
            }
    $myCol += $Details
    }
}
$myCol | Export-Csv -NoTypeInformation "C:\PartitionAlignment.csv"
#$myCol | Export-Clixml "C:\PartitionAlignment.xml"

PowerCLI: VMware Backup Script

Searching for way’s to create easy backup’s of a few virtual machines, i came on the website gestalt it (http://gestaltit.com/all/tech/virtualization/simon/vmware-backup-powercli-script/).

On this website there is a script which will create a snapshot of a VM, then clone it (thin provisioned) and finally remove the snapshot off the original VM.

Backup Script

# Import Backup CSV
$backupinfo =  Import-Csv C:\scripts\mybackups.csv

#Set Date format for clone names
$date = Get-Date -Format "yyyyMMdd"

#Set Date format for emails
$time = (Get-Date -f "HH:MM")

#Connect to vCenter
Connect-VIServer ""

foreach ($customer in $backupinfo)
{
	$vm = Get-VM $customer.MasterVM

	#Send Start Email
	C:\scripts\backupstartedemail.ps1

	# Create new snapshot for clone
	$cloneSnap = $vm | New-Snapshot -Name "Clone Snapshot"

	# Get managed object view
	$vmView = $vm | Get-View

	# Get folder managed object reference
	$cloneFolder = $vmView.parent

	# Build clone specification
	$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
	$cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot

	# Make linked disk specification
	$cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec
	$cloneSpec.Location.Datastore = (Get-Datastore -Name $customer.BackupDS | Get-View).MoRef
	$cloneSpec.Location.Transform =  [Vmware.Vim.VirtualMachineRelocateTransformation]::sparse

	$cloneName = "$vm-$date"

	# Create clone
	$vmView.CloneVM( $cloneFolder, $cloneName, $cloneSpec )

	# Write newly created VM to stdout as confirmation
	Get-VM $cloneName

	# Remove Snapshot created for clone
	Get-Snapshot -VM (Get-VM -Name $customer.MasterVM) -Name $cloneSnap | Remove-Snapshot -confirm:$False

	#Send Complete Email
	C:\scripts\backupcompletedemail.ps1
}
#Disconnect from vCentre
Disconnect-VIServer -Confirm:$false

Send Started Email Script

#Set Date format for emails
$timestart = (Get-Date -f "HH:MM")

$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Started]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart

$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)

Send Completed Email Script

#Set Date format for emails
$timecomplete = (Get-Date -f "HH:MM")

$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Complete]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart,"
Time Completed:", $timecomplete
$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)

CSV File

The content of the csv file is very simple. This is what mine looks like:

MasterVM,BackupDS
VM1,BackupDataStore
VM2,BackupDataStore

Automating VMware with PowerShell

LAB Summary
Welcome to the Automating VMware with PowerShell: Hands-On Lab. This lab will provide you hands-on experience in writing PowerShell scripts for managing VMware using the VI Toolkit (for Windows). Each participant will create scripts that will show you how to more effectively manage your virtual infrastructure. Some familiarity with PowerShell is helpful, but is not required. 
 
LAB Objective
The objective of this lab is to introduce you to the VI Toolkit (for Windows) and show you how easy automating VMware Virtual Infrastructure management is when you use PowerShell. We will cover a wide range of topics, including things like provisioning, storage, networking and monitoring. 

 Link: http://blogs.vmware.com/vipowershell/files/vmworld_europe_2008_powershell_lab_7_manual.pdf

Or local download: [wpdm_file id=”15″]