how to schedule cmdlet ??

Oct 26, 2010 at 1:35 PM

Hi folks,

I would like to schedule a little script to export all my VMs every sunday to an external disk.

Do I have to create a PS1 file containing every cmdlet? and then run this file from the Windows task scheduler?

If someone could give me an example, it would be great !!

Thanks in advance !

 

Feb 28, 2011 at 2:01 PM

This is a piece of code that I wrote that I believe does what your looking for, it does the following:

1. Shuts down each VM
2. Takes a snapshot of the VM and waits 30 seconds
3. Starts the VM
4. Copies the Snapshot off to our DR Hyper-V server
5. Shuts down the VM and tells it to remove the snapshots (merge them)
6. Allows the snapshot to merge wiats 90 seconds
7. Starts the VM
8. Writes each step to Copy.txt 
9. moves on to the next VM

10. After all VM have been copied, mails the copy.txt to our support group. 

VM's are located in D:\VM-Config
VM Drives are located in D:\VM-Drive 
Scripts are located in D:\VM-Backup-Script 

I run this as a scheduled task using a cmd file.
The file must be run as a user that has Admin rights on both Hyper-V servers.

CMD Code:

PowerShell "D:\VM-Backup-Script\new-backup-multi.PS1" /wait

Power Shell Code: (new-backup-multi.PS1)

Set-ExecutionPolicy unrestricted -force
import-module "C:\Program Files\HyperV_Powershell\hyperv.psd1"
Remove-Item D:\VM-Backup-Script\copy.txt
$arrComps = "Server1", "Server2", "Server3"
Start-Transcript D:\VM-Backup-Script\copy.txt
foreach ($arrComps in $arrComps)
{
invoke-vmshutdown $arrComps -force
new-vmsnapshot $arrComps -force -waitstart-sleep -s 30
Start-VM $arrComps -HeartBeatTimeOut 300

$date = Get-Date -format yyyy-MM-dd
New-Item \\phys-hvb\d$\VM-Drives\$date -type directory -force
Copy-Item D:\VM-Drives\$arrComps\*.vhd \\Remote-Server\d$\VM-Drives\$date\
select-vmsnapshot $arrComps | remove-vmsnapshot -wait -tree -force
invoke-vmshutdown $arrComps -force
start-sleep -s 90
Start-VM $arrComps -HeartBeatTimeOut 300
}
Stop-Transcript

$fileData = (Get-Content "D:\VM-Backup-Script\copy.txt" | out-string)
$file = "D:\VM-Backup-Script\copy.txt"
$smtpServer = "your SMTP relay Server"
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($file)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "Your-Server@mail.com"
$msg.To.Add("Recipient@mail.com")
$msg.Subject = "Hyper-V Backup Results"
$msg.Body = $fileData
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()