Playing with Hyper-V and Powershell


 

bebe_chorando

Yesterday, for a problem of ignorant piece that sits between my computer and the chair, I almost lost my Hyper-V machines. It may be simple to build again, but I have a full AD on my VMS and lost them propbably I would get very angry.
My luck that I had snapshots of them. Then I thought, why not automate the process and generate a snapshot per day,with deleting the snapshot from past seven days (sorry my english).

It has a fantastic project called the Codeplex PowerShell Management Library for Hyper-V. I like to not reinvent the wheel but to learn how to do it. As I just needed some procedures and had just read the Amazing series on TechNet Magazine by Don Jones (Twitter|Site),

I decided to build my module functions. This also reminds me that I need to rewrite the old ones.

Obviously I have much to learn about advanced functions yet, but I think this was much better than the others I did. I try to build some reusable functions. I believe I got something.

But [CmdLetBinding ()] still confuses me a lot. Well, one step at a time Smile

My first step was looking for some documentation for “Where to Start”. I knew that WMI working with Hyper-V , then a afte a BING ,came this fantastic content for people who want to study, test and implement solutions with Hyper-V on MSDN.

Hyper-V WMI Provider

Well, after that was just starting to tweak, create 354265726 Snapshots , delete, drop, truncate, shrink datafile …. all I can do on my laptop (Huaaaaa..Huaaaaaa —> Macabre Laughter )

 

To View All my Hyper-V Machines :

Get-MyHyperVMachines

To View Only Hyper-V Machine Chewie

Get-MyHyperVMachines "Chewie"

To Create My Snapshots :

1: "Chewie","ObiWan","R2D2" |  New-SnapShotMyHyperVMachines

To Create My Snapshots in all Vms

get-MyHyperVMachines |  New-SnapShotMyHyperVMachines

To get My Snapshots  Created :

"ObiWan","Chewie","R2D2" | Get-MyHyperVSnapshots

To delete my Snapshots with 7 days past.

"ObiWan","Chewie","R2D2" | Get-MyHyperVSnapshots | where {$_.convertToDateTime($_.CreationTime) -le (get-date).adddays(-7) -and $_.description -notlike ‘*Active*’} | Remove-SnapShotMyHyperVMachines

To delete All Snapshots

 "Chewie","ObiWan","R2D2" | Get-MyHyperVSnapshots |where {$_.description -notlike ‘*Active*’} | Remove-SnapShotMyHyperVMachines 

get-MyHyperVMachines | Get-MyHyperVSnapshots |where {$_.description -notlike ‘*Active*’} | Remove-SnapShotMyHyperVMachines 

(always use where {$_.description -notlike ‘*Active*’} to no remove your VM, as I did Sad smile)

To get all my snapshots in all Vms

get-MyHyperVMachines | Get-MyHyperVSnapShots

 

As you know, Now it is Only apply the filters that you need, sorts .. etc

The Module code is :

function Get-MyHyperVMachines {

    [cmdletbinding()]
   
    Param (
            [Parameter(Position=0, Mandatory=$False ,ValueFromPipeline = $True)] [string] $HyperVName = "%" ,
            [Parameter(Position=1, Mandatory=$False ,ValueFromPipeline = $False)] [string] $HostHyperVName = $Env:COMPUTERNAME
    )
    Begin {
        $query = ""
        $HyperVVm = ""
    }
    Process {
       
            $query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName like ‘$($HyperVName)’ and Name <> ElementName"
            $HyperVVm = get-wmiobject -query $query -namespace "root\virtualization" -computername $HostHyperVName
            write-output $HyperVVm
               

    }
       

}

function Get-MyHyperVSnapShots {

    [cmdletbinding()]
   
    Param (
            [Parameter(Position=0, Mandatory=$true ,ValueFromPipeline = $True)] $HyperVName,
            [Parameter(Position=1, Mandatory=$False ,ValueFromPipeline = $False)][String] $HostHyperVName = $Env:COMPUTERNAME
   

    )
    Begin {
        $query =""
        $HyperVVm = ""
    }
    Process {
   
        switch ($HyperVName.GetType().Name)      {
            ‘String’ { $HyperVVm = get-MyHyperVMachines -HyperVName $HyperVName -HostHyperVName $HostHyperVName }
            ‘ManagementObject’ { $HyperVVm = $HyperVName }
            default { throw ‘Get-MyHyperVSnapShots:Param `$HyperVName must be a String or ManagementObject.’ }
        }   
   
       
        $HyperVVm.GetRelated("Msvm_VirtualSystemsettingData",$Null,$null,$null,"SettingData","ManagedElement", $false,$null) | Sort-Object CreationTime -Descending

    }
   
}   

function New-SnapShotMyHyperVMachines {

    [cmdletbinding()]
   
    Param (
            [Parameter(Position=0, Mandatory=$true ,ValueFromPipeline = $True)] $HyperVMachine,
            [Parameter(Position=1, Mandatory=$False ,ValueFromPipeline = $False)][String] $HostHyperVName = $Env:COMPUTERNAME

    )
    Begin {
        $query =""
        $HyperVVm = ""
    }
    Process {
       
            switch ($HyperVMachine.GetType().Name)    {
                ‘String’ { $MyHyperVObject = get-MyHyperVMachines -HyperVName $HyperVMachine -HostHyperVName $HostHyperVName }
                ‘ManagementObject’ { $MyHyperVObject = $HyperVMachine }
                default { throw ‘New-SnapShotMyHyperVMachines:Param `$HyperVMachine must be a String or ManagementObject.’ }
            }   

            $HyperVMachineNew =Get-WmiObject -ComputerName $MyHyperVObject.__server -NameSpace   "root\virtualization"  -Class "MsVM_virtualSystemManagementService"
            $Return = $HyperVMachineNew.CreateVirtualSystemSnapshot($MyHyperVObject)

            if ($Return.ReturnValue  -eq 4096 -or $Return -eq 0) {
                $Msg = "Hyper-V Machine $($HyperVMachine.ElementName) Snapshot with Sucesses in $(get-date -format ‘yyyy-MM-dd hh:mm:ss’)"
            } else {
                $Msg = "Hyper-V Machine $($HyperVMachine.ElementName) Error. Number $($Return.ReturnValue)"
            }
            $msg
            $Msg | out-file -FilePath (Join-Path $HOME "HyperVLog_$(get-date -format ‘yyyyy-MM-dd’).log") -Append
   
   

    }
}

function Remove-SnapShotMyHyperVMachines {

    [cmdletbinding()]
   
    Param (
            [Parameter(Position=0, Mandatory=$true ,ValueFromPipeline = $True)] $HyperVSnapShot

    )
    Begin {
        $query =""
        $HyperVVm = ""
    }
    Process {
   
            if ($HyperVSnapShot.GetType().Name -ne ‘ManagementObject’) {

                throw ‘Remove-SnapShotMyHyperVMachines:Param `$HyperVSnapShot must be a ManagementObject.’
            }               
            $HyperVSnapshotRemove =Get-WmiObject -ComputerName $HyperVSnapShot.__Server -NameSpace   "root\virtualization" -Class "MsVM_virtualSystemManagementService"

            $Return = $HyperVSnapshotRemove.RemoveVirtualSystemSnapshot($HyperVSnapShot)
           
            if ($Return.ReturnValue  -eq 4096 -or $Return -eq 0) {
                $Msg = "Hyper-V Machine $($HyperVSnapShot.ElementName) Snapshot Removed with Sucesses in $(get-date -format ‘yyyy-MM-dd hh:mm:ss’)"
            } else {
                $Msg = "Hyper-V Machine $($HyperVSnapShot.ElementName) Error. Number $($Return.ReturnValue)"
            }
            $msg
            $Msg | out-file -FilePath (Join-Path $HOME "HyperVLog_$(get-date -format ‘yyyyy-MM-dd’).log") -Append
   
           
    }
}

 

I am trying to post with code snippet in the new Writer, but it not helps.. One advice, do not use Sad smile

Now It is just Schedule in Windows and be happy Smile

 

Done. It Is so easy ..UouuuuU..

POWERSHELL ROCKS !!!

“Beauty queen of only eighteen, she
had some trouble with herself
He was always there to help her, she
always belonged to someone else

I drove for miles and miles
And wound up at your door
I’ve had you so many times
But somehow, I want more

(CHORUS)
I don’t mind spending everyday
Out on your corner in the pouring rain
Look for the girl with the broken smile
Ask her if she wants to stay awhile
And she will be loved – 2X.”

She Will Be Loved

Maroon 5

About Laerte Junior

Laerte Junior Laerte Junior is a SQL Server specialist and an active member of WW SQL Server and the Windows PowerShell community. He also is a huge Star Wars fan (yes, he has the Darth Vader´s Helmet with the voice changer). He has a passion for DC comics and living the simple life. "May The Force be with all of us"
This entry was posted in Powershell. Bookmark the permalink.

2 Responses to Playing with Hyper-V and Powershell

  1. Felipe says:

    Muito bom Laerte, e ainda tem gente que acha que com os produtos da Microsoft não é possível trabalhar com scripts.Como estava olhando na página da codeplex realmente tem muitas opções para trabalhar com Powershell e Hyper-V.São imensas as possibilidades oferecidas pelo Powershell, sem dúvida a maneira de gerenciar esses produtos estar sendo revolucionada..Parabéns pelo artigo!

  2. Laerte says:

    Verdade velho. Mas não tem como não usar. A flexibilidade e escalabilidade que temos por linha de comando é infinitamente superior que qualquer IDE.Esse modulo eu montgei somente para estudar e nao perder minhas vms, pois o projeto do James Oneill é fantastico. É o projeto oficial da MS para trabalhar com Hyper-Ve Powershell. Da pra aprender MUITO com os cmdlets dele.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s