A simple powershell script to restore vSphere state
-
02-07-2021 - |
Вопрос
I'm very new to powershell + powercli and am in need of a hand.
We have 3 /4 hosts connected to a vCenter instance, we would like to run a powershell script that identifies which VMs are running, log the names to a file, suspends (or shutdown) the machines.
Next time the script is run, it reads the names list and powers on the relevant VMs...what is the simplest way of doing this in the PowerCLI/Powershell envrinoment.
I was thinking streamreader /writer but that seems convoluted!
Решение
Consider using Join-Path
, Set-Content
and Add-Conent
for more Powershell way. Like so,
# 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
Другие советы
This seems to do the trick! Any suggestions?
#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
}
Не связан с StackOverflow