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

[玩转系统] 使用 PowerShell 扩展 Hyper-V

作者:精品下载站 日期:2024-12-14 07:51:55 浏览:11 分类:玩电脑

使用 PowerShell 扩展 Hyper-V


最近,我一直在写有关使用 PowerShell 类型扩展作为快速完成更多工作的方法的文章。或者至少以最小的努力给我我想要的信息。我经常使用 Hyper-V,Hyper-V cmdlet 非常宝贵。虽然像 Get-VM 这样的命令提供了大量信息,但我似乎总是想要更多信息,因此我想与您分享我的 Hyper-V 相关类型扩展。即使您不需要或不使用 Hyper-V,您也可能会发现我的技术很有用。

Hyper-V 虚拟机的对象类型是 Microsoft.HyperV.PowerShell.VirtualMachine,您可以通过运行 Get-VM 并将其通过管道传递给 Get-Member 来轻松获取它。使用 Update-TypeData,我想定义许多脚本属性。这些属性的值由 PowerShell 脚本块计算。例如,我希望能够快速查看虚拟机是否缺少任何已配置的磁盘文件。我可以运行这样的命令:

[玩转系统] 使用 PowerShell 扩展 Hyper-V

但如果我经常需要这些信息,那就太多了。因此,我可以使用此脚本块创建一个脚本属性。此版本考虑到虚拟机可能有多个磁盘,其中一个或多个磁盘可能会丢失。

{
    if ($this.HardDrives) {
        #test if there are any false results
        if ( ($this | Get-VMHardDiskDrive | Test-Path) -contains $False ) {
            $False
        }
        else {
            $True
        }
    }
    else {
        #no hard drive files configured or found
        $false
    }
}

与此相关的是,我想知道虚拟机消耗了多少磁盘空间。

{ 
 $stat = Get-VMHardDiskDrive -VMName $this.vmname | Get-Item | Measure-Object -Property length -sum
 [math]::Round($stat.sum/1GB,2)
}

我还想知道配置文件的路径。这将是一个 vmcx 文件,其文件名与虚拟机的 ID 匹配。

Join-path -Path "$($this.configurationLocation)\Virtual Machines" -ChildPath "$($this.vmid).vmcx" -Resolve

为了定义这些以及其他一些内容,我在 PowerShell 配置文件脚本中使用了这样的代码。

我定义了一个哈希表,其中键是属性名称,值是我将使用的脚本块。

$extensions = @{
TestVHD = {
    if ($this.HardDrives) {
        #test if there are any false results
        if ( ($this | Get-VMHardDiskDrive | Test-Path) -contains $False ) {
            $False
        }
        else {
            $True
        }
    }
    else {
        #no hard drive files configured or found
        $false
    } 
}
ConfigurationFile = {
 Join-path -Path "$($this.configurationLocation)\Virtual Machines" -ChildPath "$($this.vmid).vmcx" -Resolve
 } 
Diskpath = {$this.Harddrives.path}
Running = { if ($this.state -eq 'Running') {$True} else { $False}}
SizeGB = { 
 $stat = Get-VMHardDiskDrive -VMName $this.vmname | Get-Item | Measure-Object -Property length -sum
 [math]::Round($stat.sum/1GB,2)
  }
}

接下来,我定义一个参数哈希表,我将使用 Update-TypeData 对其进行展开。

$params = @{
  TypeName = 'Microsoft.HyperV.PowerShell.VirtualMachine' 
  MemberType = 'ScriptProperty'
  MemberName = ''
  Value = ''
  Force = $True
}

最后一步是枚举扩展并更新类型数据。

$extensions.GetEnumerator() | foreach {
 $params.memberName = $_.key
 $params.value = $_.value
 # Write-Host "Creating script property $($_.key)" -ForegroundColor cyan
 Update-Typedata @params
}

通过使用哈希表,我的代码变得井井有条并且更易于阅读。

[玩转系统] 使用 PowerShell 扩展 Hyper-V

现在我可以运行这样的命令:

[玩转系统] 使用 PowerShell 扩展 Hyper-V

我喜欢 PowerShell 提供的灵活性来满足的需求。一如既往,欢迎提出意见和反馈。

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

取消回复欢迎 发表评论:

关灯