Announcement

Collapse
No announcement yet.

Nightly P2V With 1 Day Backup Script help need

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Nightly P2V With 1 Day Backup Script help need

    The script is supposed to send an email when the process is complete. The email should say whether or not the job is sucessfull or fails. Currently it does write to the event log and say sucess if it is sucessfull or failed if it fails but the email portion fails. pls fix it
    Attached Files

  • #2
    Re: Nightly P2V With 1 Day Backup Script help need

    Archive is invalid

    Can you post the script directly in your post (use CODE tags)
    Tom Jones
    MCT, MCSE (2000:Security & 2003), MCSA:Security & Messaging, MCDBA, MCDST, MCITP(EA, EMA, SA, EDA, ES, CS), MCTS, MCP, Sec+
    PhD, MSc, FIAP, MIITT
    IT Trainer / Consultant
    Ossian Ltd
    Scotland

    ** Remember to give credit where credit is due and leave reputation points where appropriate **

    Comment


    • #3
      Re: Nightly P2V With 1 Day Backup Script help need

      I think this one will be OK. check it and see.

      thanx
      Attached Files

      Comment


      • #4
        Re: Nightly P2V With 1 Day Backup Script help need

        That is bad as well. Please do what Ossian asked and post the text of the code within a post, and use the CODE tags around the code.
        ** Remember to give credit where credit is due and leave reputation points where appropriate **

        Comment


        • #5
          Re: Nightly P2V With 1 Day Backup Script help need

          Roger, I saw you had posted the code yesterday -- why did you remove it?
          Also, not many people want to open an unknown zip file -- I used a virtual PC -- just in case of viruses
          Tom Jones
          MCT, MCSE (2000:Security & 2003), MCSA:Security & Messaging, MCDBA, MCDST, MCITP(EA, EMA, SA, EDA, ES, CS), MCTS, MCP, Sec+
          PhD, MSc, FIAP, MIITT
          IT Trainer / Consultant
          Ossian Ltd
          Scotland

          ** Remember to give credit where credit is due and leave reputation points where appropriate **

          Comment


          • #6
            Re: Nightly P2V With 1 Day Backup Script help need

            If you do decide to post the code, don't foget to sanitse it and substitute any identifying Domain Names or email addresses with bogus ones.
            1 1 was a racehorse.
            2 2 was 1 2.
            1 1 1 1 race 1 day,
            2 2 1 1 2

            Comment


            • #7
              Re: Nightly P2V With 1 Day Backup Script help need

              Third Part
              Code:
              # Inserts a Date/Time Stamp & Stops Logging of the PowerShell Session
                                  Write-Host "P2V Conversion - Script Finished - $(Get-Date -format F)"
                                  Stop-Transcript
              
                                  # Write an event in Event Log - Application
                                  $evt = New-Object System.Diagnostics.EventLog("Application")
                                  $evt.Source = "VMM Custom Event"
                                  $infoevent = [System.Diagnostics.EventLogEntryType]::Error
                                  $evt.WriteEntry("The P2V Conversion of $SourceComputer failed.", $infoevent, 70)
              
                                  # Send mail with status of task
                                  $attachment = New-Object System.Net.Mail.Attachment($LogFileSourceComputer)
                                  $SmtpClient = New-Object System.Net.Mail.SmtpClient
                                  $MailMessage = New-Object System.Net.Mail.MailMessage
                                  $SmtpClient.Host = $smtpServer
                                  $mailmessage.From = "[email protected]"
                                  $mailmessage.To.Add("[email protected]")
                                  $mailmessage.Subject = "The P2V Conversion for $SourceComputer failed"
                                  $mailmessage.IsBodyHtml = 1
                                  $mailmessage.Body = "Results of P2V for <em>$SourceComputer</em>"
                                  $mailmessage.Attachments.Add($attachment)
                                  $SmtpClient.Send($mailmessage)
                              }
                              else
                              {
                                  # Inserts a Date/Time Stamp & Stops Logging of the PowerShell Session
                                  Write-Host "P2V Conversion - Script Finished - $(Get-Date -format F)"
                                  Stop-Transcript
              
                                  # Write an event in Event Log - Application
                                  $evt = New-Object System.Diagnostics.EventLog("Application")
                                  $evt.Source = "VMM Custom Event"
                                  $infoevent = [System.Diagnostics.EventLogEntryType]::Information
                                  $evt.WriteEntry("The P2V Conversion of $SourceComputer was successful.", $infoevent, 70)
              
                                  # Send mail with status of task
                                  $attachment = New-Object System.Net.Mail.Attachment($LogFileSourceComputer)
                                  $SmtpClient = New-Object System.Net.Mail.SmtpClient
                                  $MailMessage = New-Object System.Net.Mail.MailMessage
                                  $smtp.Host = $smtpServer
                                  $message.From = New-Object System.Net.Mail.MailAddress($from)
              
                                  foreach ($a in $to.Split(";"))
                                  {
                                      $address = New-Object System.Net.Mail.MailAddress($a.Trim())
                                      $message.To.Add($address)
                                  }
              
                                  $mailmessage.Subject = "The P2V Conversion for $SourceComputer was successful"
                                  $mailmessage.IsBodyHtml = 1
                                  $mailmessage.Body = "Results of P2V for <em>$SourceComputer</em>"
                                  $mailmessage.Attachments.Add($attachment)
                                  $SmtpClient.Send($mailmessage)
                              }
                          }
              
                      else
                      {
                          Write-Host "ERROR connecting to source computer $SourceComputer" -ForegroundColor Red
                          Stop-Transcript
              
                          # Write an event in Event Log - Application
                          $evt = New-Object System.Diagnostics.EventLog("Application")
                          $evt.Source = "VMM Custom Event"
                          $infoevent = [System.Diagnostics.EventLogEntryType]::Error
                          $evt.WriteEntry("ERROR connecting to source computer $SourceComputer", $infoevent, 70)
              
                          # Send mail with status of task
                          $attachment = New-Object System.Net.Mail.Attachment($LogFileSourceComputer)
                          $SmtpClient = New-Object System.Net.Mail.SmtpClient
                          $MailMessage = New-Object System.Net.Mail.MailMessage
                          $smtp.Host = $smtpServer
                          $message.From = New-Object System.Net.Mail.MailAddress($from)
              
                          foreach ($a in $to.Split(";"))
                          {
                              $address = New-Object System.Net.Mail.MailAddress($a.Trim())
                              $message.To.Add($address)
                          }
              
                          $mailmessage.Subject = "ERROR connecting to source computer $SourceComputer"
                          $mailmessage.IsBodyHtml = 1
                          $mailmessage.Body = "ERROR connecting to source computer <em>$SourceComputer</em>"
                          $mailmessage.Attachments.Add($attachment)
                          $SmtpClient.Send($mailmessage)
                      }
                  }
              Last edited by ahinson; 10th July 2009, 14:57.

              Comment


              • #8
                Re: Nightly P2V With 1 Day Backup Script help need

                Second Part
                Code:
                # Pauses 10 Seconds to Allow Script Section to Finish Before Continuing to Next section
                                Start-Sleep -s 10
                
                                # ------------------------------------------------------------------------------
                                # P2V Conversion Script
                                # ------------------------------------------------------------------------------
                                Write-Host "P2V Conversion - Script Started - $(Get-Date -format F)"
                                Write-Host ""
                
                                # These 2 lines opens the encrypted password file and stores the credentials for the script to use
                                # domain\username
                                $OwnerUser = $env:userdomain + "\" + $env:username
                                $OwnerPass = Get-Content "$VMMLibrarySharePathKeyVal\Scripts\credentials.txt" | ConvertTo-SecureString
                                $Credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $OwnerUser,$OwnerPass
                
                                # Created a Machine Cofiguration to Store Info about Hardware, Disks, OS, etc
                                $JobGroupID = [System.Guid]::NewGuid()
                                New-MachineConfig -VMMServer $VMMServer -SourceComputerName "$SourceComputer" -Credential $Credential
                                $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                while ($JobStatus.IsCompleted -eq $true -and $JobStatus.Status -eq 'Failed')
                                {
                                    #Write-Host "While 1" + $JobStatus
                                    Start-Sleep -Seconds 60
                                    $JobStatus = Get-Job -All | where {$_.ID -eq "$JobGroupID"}
                                    for ($i=1; $i -le 3; $i++)
                                    {
                                        Write-Host "New-MachineConfig:" $i
                                        Restart-Job -Job $JobGroupID
                                        $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                        while ($JobStatus.IsCompleted -eq $true -and $JobStatus.Status -eq 'Failed')
                                        {
                                            Start-Sleep -Seconds 10
                                            $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                            #Write-Host "While 2" + $JobStatus
                                        }
                                        if ($JobStatus.Status -ne 'Failed')
                                        {
                                            $i=4
                                        }
                                        else
                                        {
                                            Start-Sleep -Seconds 10
                                        }
                                    }
                                }
                
                                $JobGroupID = [System.Guid]::NewGuid()
                                # Creates the Network Cards & Stores the Info in the JobGroup
                                $VMHost = Get-VMHost -VMMServer $VMMServer | where {$_.Name -eq $VMMServer}
                                $MachineConfig = Get-MachineConfig -VMMServer $VMMServer | where {$_.Name -eq "$SourceComputer"}
                                ForEach ($NetworkAdapter in (($MachineConfig).NetworkAdapters))
                                {
                                    $MAC = $NetworkAdapter.MACAddress
                                    New-P2V -VMMServer $VMMServer -VMHost $VMHost -JobGroup $JobGroupID -SourceNetworkConnectionID $MAC -PhysicalAddress $MAC -PhysicalAddressType Static -NoConnection -MachineConfig $MachineConfig
                                    Start-Sleep -Seconds 10
                                    # Write-Host "ForEach - NetworkAdapter"
                                }
                
                                # Creates the Drives & Stores the Info in the JobGroup
                                $VMHost = Get-VMHost -VMMServer $VMMServer | where {$_.Name -eq $VMMServer}
                                $MachineConfig = Get-MachineConfig -VMMServer $VMMServer | where {$_.Name -eq "$SourceComputer"}
                                ForEach ($Volume in (($MachineConfig).Volumes))
                                {
                                    $VolumeDeviceID = $Volume.DeviceID
                                    $Bus = $Volume.FirstPartitionDiskIndex
                                    $Lun = $Volume.FirstPartitionIndex
                                    New-P2V -VMMServer $VMMServer -VMHost $VMHost -JobGroup $JobGroupID -VolumeDeviceID $VolumeDeviceID -Dynamic -IDE -Bus $Bus -Lun $Lun -MachineConfig $MachineConfig
                                    Start-Sleep -Seconds 10
                                    # Write-Host "ForEach - Volume"
                                }
                
                                # Gathers the Data Stored in the Job Group and Uses it to Perform the P2V Conversion
                                $VMHost = Get-VMHost -VMMServer $VMMServer | where {$_.Name -eq $VMMServer}
                                $MachineConfig = Get-MachineConfig -VMMServer $VMMServer | where {$_.Name -eq "$SourceComputer"}
                
                                New-P2V -Credential $Credential -VMMServer $VMMServer -VMHost $VMHost -Path $RootFolder -Owner $OwnerUser -JobGroup $JobGroupID -Trigger -Name $SourceComputer -MachineConfig $MachineConfig -CPUCount $MachineConfig.CPUCount -MemoryMB $MemoryMB -RunAsSystem -StartAction NeverAutoTurnOnVM -DelayStart 0 -StopAction SaveVM -UseHardwareAssistedVirtualization $false
                                $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                while ($JobStatus.IsCompleted -eq $false)
                                {
                                    Start-Sleep -Seconds 60
                                    $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                    # Write-Host "While 3" + $JobStatus
                                }
                                $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                if ($JobStatus.IsCompleted -eq $true -and $JobStatus.Status -eq 'Failed')
                                {
                                    for ($i=1; $i -le 3; $i++)
                                    {
                                        Write-Host "New-P2V:" $i
                
                                        # Stop Hyper-V and Virtual Machine Manager services
                                        Get-Service -Name vmms | Stop-Service
                                        Get-Service -Name nvspwmi | Stop-Service
                                        Get-Service -Name vhdsvc | Stop-Service
                                        Get-Service -Name vds | Stop-Service
                                        Get-Service -Name vmmservice | Stop-Service
                                        Get-Service -Name vmmagent | Stop-Service
                                        Get-VM -Name $SourceComputer | where {$_.HostType -eq 'VMHost'} | Remove-VM
                
                                        # Removes VM files from "D:\Virtual Machines" folder
                                        Remove-Item "$RootFolder\$SourceComputer" -force
                
                                        # Start Hyper-V and Virtual Machine Manager services
                                        Start-Service -Name vmms
                                        Start-Service -Name nvspwmi
                                        Start-Service -Name vhdsvc
                                        Start-Service -Name vds
                                        Start-Service -Name vmmservice
                                        Start-Service -Name vmmagent
                                        Restart-Job -Job $JobGroupID
                                        $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                        while ($JobStatus.IsCompleted -eq $false)
                                        {
                                            Start-Sleep -Seconds 60
                                            $JobStatus = Get-Job | where {$_.ID -eq "$JobGroupID"}
                                            # Write-Host "While 4" + $JobStatus
                                        }
                                        if ($JobStatus.Status -ne 'Failed')
                                        {
                                            $i=4
                                        }
                                        else
                                        {
                                            Start-Sleep -Seconds 900
                                        }
                                    }
                Last edited by ahinson; 10th July 2009, 14:56.

                Comment


                • #9
                  Re: Nightly P2V With 1 Day Backup Script help need

                  First Part
                  Code:
                  param ([string] $VMMServer, [string] $SourceComputer, [int] $MemoryMB, [string] $smtpServer, [string] $from, [string] $to)
                  if(("-?", "-help") -contains $args[0])
                  {
                          Write-Host ""
                          Write-Host "Script require parameters to run! See usage" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                          exit 0
                  }
                  if (($VMMServer -eq "") -or ($SourceComputer -eq ""))
                      {
                          Write-Host ""
                          Write-Host "VMM Server and Source Computer is required!" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                      }
                  elseif ($MemoryMB -eq "")
                      {
                          Write-Host ""
                          Write-Host "Memory size in MB is required!" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                      }
                  elseif ($smtpServer -eq "")
                      {
                          Write-Host ""
                          Write-Host "SMTP server address required!" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                      }
                  elseif ($from -eq "")
                      {
                          Write-Host ""
                          Write-Host "Sender address is required!" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                      }
                  elseif ($to -eq "")
                      {
                          Write-Host ""
                          Write-Host "Recipient address or addresses list (string separed with semicolon) is required!" -ForegroundColor Red
                          Write-Host "Usage:" $MyInvocation.MyCommand.Name "<VMMServerName> <SourceComputerName> <MemorySizeMB> <smtpServer> <from> <to>" -ForegroundColor Red
                          Write-Host "e.g.:" $MyInvocation.MyCommand.Name "imibackup.imi.com accounting01 1408 smtp.com [email protected] ""[email protected]; [email protected]""" -ForegroundColor Red
                          Write-Host ""
                      }
                  else
                      {
                          Write-Host ""
                          Write-Host "Start to run script:" $MyInvocation.MyCommand.Name $VMMServer $SourceComputer $MemoryMB -ForegroundColor Green
                          Write-Host ""
                          $VMMLibrarySharePath = "HKLM:\Software\Microsoft\Microsoft System Center Virtual Machine Manager Server\Settings\Library"
                          $VMMLibrarySharePathKey = Get-ItemProperty $VMMLibrarySharePath
                          $VMMLibrarySharePathKeyVal = $VMMLibrarySharePathKey.LibrarySharePath
                          Write-Host "VMMLibrarySharePath:" $VMMLibrarySharePathKeyVal
                          $RootDrive = (Get-Item $VMMLibrarySharePathKeyVal).fullname | Split-Path –qualifier
                          Write-Host "Root drive: " $RootDrive
                          $RootFolder = "$RootDrive\Virtual Machines"
                          $RootFolderP2VLogs = "$RootFolder\P2V Logs"
                          trap [Exception]
                          {
                              $now = get-date
                              $smtp = New-Object System.Net.Mail.SmtpClient
                              $message = New-Object System.Net.Mail.MailMessage
                              $smtp.Host = $smtpServer
                              $message.From = New-Object System.Net.Mail.MailAddress($from)
                              foreach ($a in $to.Split(";"))
                              {
                                  $address = New-Object System.Net.Mail.MailAddress($a.Trim())
                                  $message.To.Add($address)
                              }
                              $message.Subject = "The P2V Conversion for $SourceComputer failed"
                              $message.IsBodyHtml = 1
                              $message.Body = "<font color=red>An error has occured!</font><br/><br/>Message:<br/>" + $_.Exception.Message + "<br/><br/>Type:<br/>" + $_.Exception.GetType().FullName + "<br/><br/>Stacktrace:<br/>" + $_.Exception.StackTrace + "<br/><br/>Time:<br/>" + $now            
                              $SourceComputer = ($SourceComputer).ToLower()
                              $LogFileSourceComputer = "$RootFolderP2VLogs\$(Get-Date -uformat '%Y_%m_%d')_$SourceComputer.log"            
                              if(test-path $LogFileSourceComputer)
                              {
                                  Stop-Transcript
                                  $attachment = New-Object System.Net.Mail.Attachment($LogFileSourceComputer)
                                  $message.Attachments.Add($attachment)
                              }
                              #$smtp.Send($message)
                              $evt = New-Object System.Diagnostics.EventLog("Application")
                              $evt.Source = "VMM Custom Event"
                              $infoevent = [System.Diagnostics.EventLogEntryType]::Error            
                              break
                          }
                          if (Test-Path $RootFolder -pathType container)
                          {
                              Write-Host "The folder $RootFolder exists"
                          }
                          else
                          {
                              Write-Host "The folder $RootFolder does not exist, creating folder..."
                              New-Item $RootFolder -type directory
                          }
                          if (Test-Path $RootFolderP2VLogs -pathType container)
                          {
                              Write-Host "The folder $RootFolderP2VLogs exists"
                          }
                          else
                          {
                              Write-Host "The folder $RootFolderP2VLogs does not exist, creating folder..."
                              New-Item $RootFolderP2VLogs -type directory
                          }        
                          $Days = 7
                          Write-Host 'Clean out logs older than' $Days 'days...'
                          $OldFiles = (Get-Date).AddDays(-$Days)
                          Get-ChildItem "$RootFolderP2VLogs" -Include *.log -Recurse | where {-not $_.PSIsContainer -and ($_.lastWriteTime -le $OldFiles)} | Remove-Item -Force
                          # Starts Logging of the PowerShell Session and inserts a Date/Time Stamp
                          $SourceComputer = ($SourceComputer).ToLower()
                          $LogFileSourceComputer = "$RootFolderP2VLogs\$(Get-Date -uformat '%Y_%m_%d')_$SourceComputer.log"
                          Write-Host $LogFileSourceComputer
                          Start-Transcript -path $LogFileSourceComputer -NoClobber -Append
                          $querySourceComputer = Get-WmiObject -ComputerName $SourceComputer -Namespace root\CIMV2 -Class Win32_Service -Filter "name='Winmgmt'" -ErrorAction Stop
                          if ($querySourceComputer.Status -eq 'OK')
                          {
                                  Write-Host 'Connection OK'                
                                  Write-Host "Remove VM for Virtual Machine Host Library - Script Started - $(Get-Date -format F)"
                                  Write-Host ""                
                                  $LibraryServer = Get-LibraryServer -VMMServer $VMMServer | where {$_.Name -eq $VMMServer}
                                  $VMLibraryCount = (@(Get-VM -VMMServer $VMMServer | where {$_.LibraryServer.Name -eq $LibraryServer -and $_.Name -eq $SourceComputer})).Count
                                  if ($VMLibraryCount -eq 0)
                                  {
                                      Write-Host ""
                                      Write-Host "No VM found in Library Server to be removed for $SourceComputer"
                                      Write-Host ""
                                      Start-Sleep -s 10
                                  }
                                  else
                                  {
                                      $VMLibrary = Get-VM -VMMServer $VMMServer | where {$_.LibraryServer.Name -eq $LibraryServer -and $_.Name -eq $SourceComputer}
                                      $VMMCount = (@(Get-VM -VMMServer $VMMServer -Name $SourceComputer | where {$_.VMHost.Name -eq $VMMServer})).Count
                                      if ($VMMCount -eq 0)
                                      {
                                          Write-Host ""
                                          Write-Host "No VM found in Virtual Machines for $SourceComputer, current VM from Library Server if exists will not be removed"
                                          Write-Host ""
                                          Start-Sleep -s 10
                                      }
                                      else
                                      {
                                          $VMM = Get-VM -VMMServer $VMMServer -Name $SourceComputer | where {$_.VMHost.Name -eq $VMMServer}
                                          if ($VMM.Status -eq "P2VCreationFailed")
                                          {
                                              Write-Host ""
                                              Write-Host "Previous P2V failed for $SourceComputer, current VM stored in Library Server will not be removed, but FAILED P2V will be removed"
                                              Write-Host ""
                                              Remove-VM -VM $VMM
                                              Start-Sleep -s 60
                                          }
                                          else
                                          {
                                              Write-Host ""
                                              Write-Host "Found VM in Library Server to be removed for $SourceComputer"
                                              Write-Host ""
                                              Remove-VM -VM $VMLibrary
                                              Start-Sleep -s 300
                                              }
                                          }
                                      }
                                  Write-Host "Remove VM for Virtual Machine Host Library - Script Finished - $(Get-Date -format F)"
                  Last edited by ahinson; 10th July 2009, 14:57.

                  Comment


                  • #10
                    Re: Nightly P2V With 1 Day Backup Script help need

                    Why'd you post them in reverse order? Next time please use the CODE format around them like we asked. Makes the characters more uniform.
                    ** Remember to give credit where credit is due and leave reputation points where appropriate **

                    Comment

                    Working...
                    X