Powershell:在断电情况下移动虚拟机的脚本?

时间:2017-07-18 12:13:19

标签: powershell

我正在编写一个PowerShell脚本,如果出现UPS故障或断电,它会将所有VM移动到另一个群集中的相应服务器。

如果发生断电,每台UPS都会在特定文件夹中创建一个日志文件,我的脚本应检测哪个UPS断电。

脚本应该每5分钟运行一次,如果UPS3断电,只需要关闭备份服务器。

我是PowerShell的新手,所以任何帮助或信息都会很棒。

这是我的概念:

$text1 = "UPS1"
$text2 = "UPS2"
$text3 = "UPS3"
$path = "C:\UPS"
$logfile = "C:\UPS\logs"
$timer = 10000
$date = Get-Date -Format g

$search_results = Get-ChildItem -Path $path | Where-Object { ((!$_.PSIsContainer))}

foreach ($file in $search_results) {
    if ($file.Name -contains $text1) {
        Get-VM -Location (Get-VMHost ‘ESX01’) | Move-VM -Destination (GetVM-Host ‘ESX03’)
        Get-VM -Location (Get-VMHost ‘ESX02’) | Move-VM -Destination (GetVM-Host ‘ESX04’)
        Write-Output "VMs moved from 01 to 03 and 02 to 04!" | Out-File $logfile -Append
    }
    elseif ($file.Name -contains $text2) {
        Get-VM -Location (Get-VMHost ‘ESX03’) | Move-VM -Destination (GetVM-Host ‘ESX01’)
        Get-VM -Location (Get-VMHost ‘ESX04’) | Move-VM -Destination (GetVM-Host ‘ESX02’)
        Write-Output "VMs moved from 03 to 01 and 04 to 02!" | Out-File $logfile -Append
    }
    elseif ($file.Name -contains $text3) {
        $timer.start
        Stop-VMGuest -VM "Backup"
        Write-Output "UPS3 lost power, shutdown of the backup server initiated!" | Out-File $logfile -Append
    }
}
else
Out-File $logfile -InputObject $date
Write-Output "Alle UPS are running!" | Out-File $logfile -Append

-WhatIf

1 个答案:

答案 0 :(得分:1)

-FileGet-ChildItem一起使用只返回文件,这意味着您不再需要使用Where-Object进行过滤。

另外,由于您仅使用Name属性,因此使用Select-Object -ExpandProperty Name表示您每次都可以使用$file代替$file.Name

使用Switch Statement代替多个if/else可以让代码更易于管理:

$path = "C:\UPS"
$logfile = "C:\UPS\log.txt"
$date = Get-Date -Format g

$files = Get-ChildItem -Path $path -File | Select-Object -ExpandProperty Name

foreach ($file in $files) {
    switch -Wildcard ($file) { 
        "*UPS1*" {
            Get-VM -Location (Get-VMHost "ESX01") | Move-VM -Destination (GetVM-Host "ESX03")
            Get-VM -Location (Get-VMHost "ESX02") | Move-VM -Destination (GetVM-Host "ESX04")
            Add-Content $logfile "`n$date - VMs moved from 01 to 03 and 02 to 04!"
        }
        "*UPS2*" {
            Get-VM -Location (Get-VMHost "ESX03") | Move-VM -Destination (GetVM-Host "ESX01")
            Get-VM -Location (Get-VMHost "ESX04") | Move-VM -Destination (GetVM-Host "ESX02")
            Add-Content $logfile "`n$date - VMs moved from 03 to 01 and 04 to 02!"
        }
        "*UPS3*" {
            Stop-VMGuest -VM "Backup"
            Add-Content $logfile "`n$date - UPS3 lost power, shutdown of the backup server initiated!"
        }
        default {
            Add-Content $logfile "`n$date - All UPS are running!"
        }
    }
}

我无法测试您的Get-VM / Move-VM命令,因为我没有VMWare环境,所以我认为它们工作正常。< / p>

相关问题