0

我对 powershell + powercli 很陌生,需要帮助。

我们有 3 /4 台主机连接到 vCenter 实例,我们想运行一个 powershell 脚本来识别哪些虚拟机正在运行,将名称记录到文件中,暂停(或关闭)机器。

下次运行该脚本时,它会读取名称列表并打开相关虚拟机的电源……在 PowerCLI/Powershell 环境中执行此操作的最简单方法是什么。

我在想streamreader / writer,但这似乎很复杂!

4

2 回答 2

0

这似乎可以解决问题!有什么建议么?

#File Storage Path
$filePath = "D:\"

#Get the host lists and sort
$ESXHost= Get-VMHost | Sort-Object -Property Name

function storeEnvironment
{#Store the powered VM list to a simple file
    #Use Streamwriter for simpler output, just a string name
    $PowerFile = New-Object System.IO.StreamWriter($filePath+"MTS_ON.txt")

    foreach($objHost in $ESXHost)
    {
        $PoweredVMs += Get-VMHost -Name $objHost | Get-VM | where {$_.Powerstate -eq "PoweredON" }
        foreach($objVM in $PoweredVMs)
        {
            $PowerFile.WriteLine($objVM)
            Get-VM -Name $objVM | Suspend-VM
        }
    } 
    $PowerFile.close()
}

function restoreEnvironment
{
    [array] $VMs = Get-Content -Path $filePath"MTS_ON.txt"
    foreach($VM in $VMs)
    {
        Get-VM -Name $VM | Start-VM
    }
    #Delete the configuration file
    Remove-Item $filePath"MTS_ON.txt"
}

#MAIN

#Test to see if the config file exists
if(Test-Path $filePath"MTS_ON.txt") 
{
    Write-Host "Restore from file? [Y]es or [N]o"
    $response = Read-Host
    if($response -eq "Y")
    {
        #Use file to restore VMs
        Write-Host "Restore Environment"
        restoreEnvironment
    }
    else
    {
        #Delete the configuration file
        Remove-Item $filePath"MTS_ON.txt"
    }   
}
else
{#Save the powered VMs to a file
    Write-Host "Saving Environment"
    storeEnvironment
}
于 2012-09-19T08:24:52.103 回答
0

考虑使用Join-Path,Set-ContentAdd-Conent更多的 Powershell 方式。像这样,

# Combine $filepath and MTS_ON.txt, adds slashes if need be
$pfile = join-path $filePath "MTS_ON.txt" 
# Create empty file or truncate existing one
set-content -path $pfile -value $([String]::Empty) 

foreach($objHost in $ESXHost) {
    $PoweredVMs += Get-VMHost -Name $objHost | Get-VM | where {$_.Powerstate -eq "PoweredON" }
    foreach($objVM in $PoweredVMs) {
        add-content -path $pfile -value $objVM
        Get-VM -Name $objVM | Suspend-VM
    }
} # No need to close the pfile
于 2012-09-19T09:40:24.760 回答