【问题标题】:backup of all vms on hyper v备份 hyper v 上的所有虚拟机
【发布时间】:2015-04-19 18:01:36
【问题描述】:

我是 powershell 脚本的新手,请帮助我在脚本中进行少量编辑。基本上我想安排一个脚本,它会自动备份 hyper v. windows 2012/2012 r2 上的所有服务器。我得到了一个代码,它基本上要求用户提供参数,然后它需要备份。我整理出来的是我们可以做两件事 1) 创建一个 .txt 文件,该文件将包含 hyper v 上的所有 vm 名称,但更新该文件时,每当我们添加新的 vm 时,都会很忙。所以我不会更喜欢这样做。 2)我们可以删除从用户那里获取输入的函数并在某处添加“get-vm”命令?但我无法做到这一点:/有人可以帮我这样做吗?下面是我要使用的代码。

#requires -version 3.0
#requires -module Hyper-V

<#
.SYNOPSIS
Export virtual machines
.DESCRIPTION
This utility will export virtual machines to a target destination. By default
it will create a folder using the format:

Weekly_Year_Month_Day_HourSecond

The script will delete the oldest folder once 4 subfolders have been created.
Use the -Monthly parameter to do the same thing but for folders that begin
with Monthly, i.e. Monthly_Year_Month_Day_HourSecond.

Because the export process can be time consuming, you can use the -AsJob parameter
which will be passed to Export-VM. You will then get PowerShell background jobs
which you can manage with the standard job cmdlets.

This script must be run as an administrator in an elevated session.

.PARAMETER VM
A comma separated list of virtual machines. You can also pipe Get-VM into
this command. This parameter has an alias of Name.
.PARAMETER Path
The path to the top level backup or export folder.
.PARAMETER Monthly
Run the script in Monthly mode
.PARAMETER AsJob
Export virtual machines using background jobs
.EXAMPLE
PS C:\> get-vm chi-dc01,chi-dc02 | c:\scripts\ScheduledExport.ps1 -path e:\export

Get the virtual machines, CHI-DC01 and CHI-DC02 and pipe them to the script which will
export them to the given folder.

.EXAMPLE
PS C:\> c:\scripts\ScheduledExport.ps1 "CHI-DC01","CHI-FP01" -path E:\Export -asjob

Export virtual machines CHI-DC01 and CHI-FP01 to a weekly folder under E:\Export.

.EXAMPLE
PS C:\> get-content c:\work\vms.txt | c:\scripts\ScheduledExport.ps1 -asjob -monthly

Read the text file, vms.txt, and pass each virtual machine name to the script. This will
use the Monthly backup folders. Exports will be done as jobs.

.LINK
Get-VM
Export-VM
#>

[cmdletbinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Position=0,Mandatory=$True,
HelpMessage="Enter the virtual machine name or names",
ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[Alias("name")]
[string[]]$VM,

[Parameter(Position=1)]
[ValidateNotNullorEmpty()]
[string]$Path = "C:\work\export",

[Parameter(Position=2)]
[switch]$Monthly,

[Parameter(Position=3)]
[switch]$AsJob
)

Begin {

#define some variables if we are doing weekly or monthly backups
if ($monthly) {
  $type = "Monthly"
  $retain = 2
}
else {
   $type = "Weekly"
   $retain = 4
}

Write-Verbose "Processing $type backups. Retaining last $retain."

#get backup directory list
Try {
 Write-Verbose "Checking $path for subfolders"

 #get only directories under the path that start with Weekly or Monthly
 $subFolders =  dir -Path $path\$type* -Directory -ErrorAction Stop
}
Catch {
    Write-Warning "Failed to enumerate folders from $path"
    #bail out of the script
    return
}

#check if any backup folders
if ($subFolders) {
    #if found, get count
    Write-Verbose "Found $($subfolders.count) folder(s)"

    #if more than the value of $retain, delete oldest one
    if ($subFolders.count -ge $retain ) {
       #get oldest folder based on its CreationTime property
       $oldest = $subFolders | sort CreationTime | Select -first 1 
       Write-Verbose "Deleting oldest folder $($oldest.fullname)"
       #delete it
       $oldest | Remove-Item -Recurse -Force
    }

 } #if $subfolders
else {
    #if none found, create first one
    Write-Verbose "No matching folders found. Creating the first folder"    
}

#create the folder
#get the current date
$now = Get-Date

#name format is Type_Year_Month_Day_HourMinute
$childPath = "{0}_{1}_{2:D2}_{3:D2}_{4:D2}{5:D2}" -f $type,$now.year,$now.month,$now.day,$now.hour,$now.minute

#create a variable that represents the new folder path
$new = Join-Path -Path $path -ChildPath $childPath

Try {
    Write-Verbose "Creating $new"
    #Create the new backup folder
    $BackupFolder = New-Item -Path $new -ItemType directory -ErrorAction Stop 
}
Catch {
  Write-Warning "Failed to create folder $new. $($_.exception.message)"
  #failed to create folder so bail out of the script
  Return
}
} #end begin

Process {

#only process if a backup folder was created
if ($BackupFolder) {
    #export VMs
    #define a hashtable of parameters to splat to Export-VM
    $exportParam = @{
     Path = $new
     Name=$Null
     ErrorAction="Stop"
    }
    if ($asjob) {
      Write-Verbose "Exporting as background job"
      $exportParam.Add("AsJob",$True)
    }

    Write-Verbose "Exporting virtual machines"
    <#
     Go through each virtual machine name, and export it using Export-VM
    #>
    foreach ($name in $VM) {
        $exportParam.Name=$name
        #if the user did not include -WhatIf then the machine will be exported
        #otherwise they will get a WhatIf message
        if ($PSCmdlet.shouldProcess($name)) {
           Try {
                Export-VM @exportParam
           }
           Catch {
            Write-Warning "Failed to export virtual machine(s). $($_.Exception.Message)"
           }
        } #whatif
    } #close foreach
} #if backup folder exists 
} #Process
End {
    Write-Host "Export script finished." -ForegroundColor Green

}

【问题讨论】:

    标签: powershell virtual-machine hyper-v windows2012


    【解决方案1】:

    Get-VMcmdlet 可以列出给定系统上的所有 VM。将其与粘贴脚本中包含的帮助文本中的示例相结合:

    get-vm chi-dc01,chi-dc02 | c:\scripts\ScheduledExport.ps1 -path e:\export 
    

    应该导致保存所有虚拟机语句,像这样

    get-vm  | c:\scripts\ScheduledExport.ps1 -path e:\export
    

    【讨论】:

    • 感谢 vonPryz 修复它! :D
    • 我该如何写网络路径“\\storage\backup”?当我尝试像 -path \\storage\backup 这样编写它时它不起作用:/ @vonPryz
    • @user4807619 你需要比这更具体。 “不起作用”究竟是什么意思?没有导出,导出损坏,位置错误,错误消息..?
    • 实际上它没有通过任务调度程序给出任何错误消息。但它在 powershell 提示符下运行良好。我在争论之后发现了缺少的“”。我写的是 -computername server 而不是 -computername "server"。它成功地进行了提示备份,但它自动停止并使用任务计划程序成功完成消息,甚至没有创建备份文件。
    【解决方案2】:

    这些操作似乎很容易出现人为错误。为什么不能使用第三方解决方案而不是脚本进行 Hyper-V 备份? (个人推荐Handy Backup,不过是因为这个解决方案是我工作中的一个,而且,也许其他公司的备份软件也可能包含Hyper-V备份功能?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多