简体   繁体   English

PowerCLI:使用多个 vCenter 服务器上的虚拟机

[英]PowerCLI: Work with VMs on multiple vCenter servers

I have a script that will power off and DeletePermanently all VMs that match a certain prefix.我有一个脚本可以关闭和删除所有匹配特定前缀的虚拟机。 I use this when testing other automation tools to make it easy to reset the lab.我在测试其他自动化工具时使用它,以便轻松重置实验室。 The script connects to multiple, pre-defined vCenter servers and then gets a list of all the VMs.该脚本连接到多个预定义的 vCenter 服务器,然后获取所有 VM 的列表。 The problem I have is that when I try to power off or delete the VMs, it says "Could not find VirtualMachine with name 'VMNAME'."我遇到的问题是,当我尝试关闭或删除 VM 时,它显示“找不到名为‘VMNAME’的虚拟机。”

Code that connects to the vCenter servers:连接到 vCenter 服务器的代码:

$vcservers = @("VC1","VC2")
Connect-VIServer $vcservers

Code that gets a list of VMs from both vCenter servers:从两个 vCenter 服务器获取虚拟机列表的代码:

$prefix = "TEST"
ForEach ($vc in $vcservers) {
    $vms += Get-VM -Server $vc | where {$_.Name -like "$prefix*"}
}

Code that powers off and deletes each VM:关闭并删除每个 VM 的代码:

ForEach ($vm in $vms) {
    $vmname = $vm.name
    if ($vm.PowerState -eq "PoweredOn") {
        Stop-VM -VM $vmname -confirm:$false
        Remove-VM -VM $vmname -DeletePermanently -confirm:$false
    }
}

I have set the "Multiple" property on the Users and AllUsers scope by using Set-PowerCLIConfiguration, so it should search all vCenter servers, but for some reason it is not working.我已经使用 Set-PowerCLIConfiguration 在 Users 和 AllUsers 范围上设置了“Multiple”属性,因此它应该搜索所有 vCenter 服务器,但由于某种原因它不起作用。

EDIT 1/25/17 Updated the code to make the $vcservers variable consistent.编辑 2017 年 125 日更新了代码以使 $vcservers 变量保持一致。

Since the first issue (related to variable naming) was resolved, I'm currently suspecting that the issue is due to PowerCLI being unsure on which VCenter the VMs you want to delete live.由于第一个问题(与变量命名相关)已解决,我目前怀疑该问题是由于 PowerCLI 不确定要在哪个 VCenter 上实时删除 VM。 Thus, you could go VCenter by vCenter instead of trying to run against all vCenters at once:因此,您可以通过 vCenter 访问 VCenter,而不是尝试一次针对所有 vCenter 运行:

$prefix = "TEST"
$vcservers = @("VC1","VC2")
ForEach ($vc in $vcservers) {
    Connect-VIServer $vc
    $vms += Get-VM -Server $vc | where {$_.Name -like "$prefix*"}

    ForEach ($vm in $vms) {
        $vmname = $vm.name
        if ($vm.PowerState -eq "PoweredOn") {
            Stop-VM -VM $vmname -confirm:$false
            Remove-VM -VM $vmname -DeletePermanently -confirm:$false
        }
    Disconnect-VIServer $vc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM