【问题标题】:A simple powershell script to restore vSphere state用于恢复 vSphere 状态的简单 powershell 脚本
【发布时间】:2012-09-18 17:08:56
【问题描述】:
我是 powershell + powercli 的新手,需要帮助。
我们有 3 /4 台主机连接到 vCenter 实例,我们想运行一个 powershell 脚本来识别哪些虚拟机正在运行,将名称记录到文件中,暂停(或关闭)机器。
下次运行该脚本时,它会读取名称列表并打开相关虚拟机的电源...在 PowerCLI/Powershell 环境中执行此操作的最简单方法是什么。
我在考虑流式阅读器/作家,但这似乎令人费解!
【问题讨论】:
标签:
powershell
powershell-2.0
virtualization
powercli
vsphere
【解决方案1】:
考虑使用Join-Path、Set-Content 和Add-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
【解决方案2】:
这似乎可以解决问题!有什么建议吗?
#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
}