一个简单的powershell脚本来恢复vSphere状态
问题描述:
我对powershell + powercli非常陌生,并且需要一只手。一个简单的powershell脚本来恢复vSphere状态
我们有3/4个主机连接到vCenter实例,我们想要运行PowerShell脚本来识别哪些虚拟机正在运行,将名称记录到文件中,暂停(或关闭)计算机。
下一次脚本运行时,它会读取名称列表并打开相关VM的电源......在PowerCLI/Powershell环境中执行此操作的最简单方法是什么?
我在想流媒体/作家,但似乎令人费解!
答
考虑使用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
答
这似乎是个伎俩!有什么建议么?
#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
}