当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] InfoWorld:自动化实时 VM 导出

作者:精品下载站 日期:2024-12-14 07:41:43 浏览:16 分类:玩电脑

InfoWorld:自动化实时 VM 导出


[玩转系统] InfoWorld:自动化实时 VM 导出

我写的剧本比彼得最初设想的要复杂一些。现在,我怀疑他的目标能否通过一句俏皮话来实现。因此,由于我需要编写一个脚本,因此我花了一些时间来使其在错误处理和参数验证等方面变得健壮。我只想开发一次脚本,为什么不彻底呢?

当我根据 Peter 的要求完成脚本时,我意识到这也可以使用 PowerShell 工作流程来解决。原始脚本的限制之一是它需要在 Hyper-V 服务器上运行。我没有包含任何连接到远程服务器的规定。我还认识到导出多个虚拟机可以并行完成。尽管我的原始脚本允许使用后台作业,这有点像并行运行。但我认为工作流程版本至少可能具有教育意义。以下是 Export-MyVM 工作流程。

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

Workflow Export-MyVM {

Param(
[Parameter(Position=0,Mandatory=$True,
HelpMessage="Enter the virtual machine name or names")]
[ValidateNotNullorEmpty()]
[Alias("name")]
[string[]]$VM,
[Parameter(Position=0,Mandatory=$True,
HelpMessage="Enter the root backup path")]
[ValidateNotNullorEmpty()]
[string]$Path,
[switch]$Monthly
)

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

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

#manage folders

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

 #get only directories under the path that start with Weekly or Monthly
 $subFolders =  Get-ChildItem -Path $path$type* -Directory -ErrorAction Stop
}
Catch {
    Write-Warning "Failed to enumerate folders from $path. $($_.Exception.Message)"
    #bail out of the script
    return
}

#check if any backup folders
if ($subFolders) {
    #if found, get count
    Write-Verbose -message "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-Object -property CreationTime | Select-Object -first 1 
       Write-Verbose -message "Deleting oldest folder $($oldest.fullname)"
       #delete it
       $oldest | Remove-Item -Recurse -Force 
    }

 } #if $subfolders
else {
    #if none found, create first one
    Write-Verbose -Message "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
$newpath = Join-Path -Path $path -ChildPath $childPath

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

#export VMs
if ($BackupFolder) {

#export each machine in parallel
foreach -parallel ($item in $VM) {
    Write-Verbose -Message "Exporting $item"

    #define a hashtable of parameters to splat to Export-VM
    $exportParam = @{
     Path = $newPath
     Name=$item
     ErrorAction="Stop"
    }
    Try {
          Export-VM @exportParam
    }
    Catch {
           Write-Warning "Failed to export virtual machine(s)."
           Throw $_
     }

    } #foreach parallel
} #if backup folder exists 

Write-Verbose -Message "Ending $workflowcommandname"

} #close workflow

尽管我删除了 WhatIf 参数,但大部分代码与原始脚本相同。您不能在工作流程中使用 SupportsShouldProcess,而且我没有时间完全编写自己的。唯一真正特定于工作流程的代码是:

#export each machine in parallel
foreach -parallel ($item in $VM) {
    Write-Verbose -Message "Exporting $item"

    #define a hashtable of parameters to splat to Export-VM
    $exportParam = @{
     Path = $newPath
     Name=$item
     ErrorAction="Stop"
    }
    Try {
          Export-VM @exportParam
    }
    Catch {
           Write-Warning "Failed to export virtual machine(s)."
           Throw $_
     }

    } #foreach parallel

也许最大的优势是,通过工作流程,我可以获得对后台作业和远程处理的自动支持。现在我可以针对 Hyper-V 服务器执行工作流程。

PS C:\> export-myvm -name 'chi-client02','chi-dctest' -path d:\backup -Verbose -AsJob -PSComputerName chi-hvr2.globomantics.local

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
100    Job100          PSWorkflowJob   Running       True            chi-hvr2.globoman... export-myvm              

PS C:\> get-job 100 -IncludeChildJob

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
100    Job100          PSWorkflowJob   Running       True            chi-hvr2.globoman... export-myvm              
101    Job101          PSWorkflowJob   Running       True            chi-hvr2.globoman... Export-MyVM

我仍然可以在我的计算机上创建 PowerShell 计划作业来运行此工作流程。

顺便说一句,我相信您知道 Altaro、Veeam 和 Unitrends 等公司(所有这些公司都为我的博客提供了支持)提供了大量 Hyper-V 备份产品。其中一些甚至有其产品的免费版本。因此,虽然您可以使用 PowerShell 导出虚拟机,但这并不意味着您应该这样做。尽管我可以看到快速而脏的备份的价值。最终,我认为有选择是一件好事。

享受。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯