我對powershell + powercli非常陌生,並且需要一隻手。一個簡單的powershell腳本來恢復vSphere狀態
我們有3/4個主機連接到vCenter實例,我們想要運行PowerShell腳本來識別哪些虛擬機正在運行,將名稱記錄到文件中,暫停(或關閉)計算機。
下一次腳本運行時,它會讀取名稱列表並打開相關VM的電源......在PowerCLI/Powershell環境中執行此操作的最簡單方法是什麼?
我在想流媒體/作家,但似乎令人費解!
我對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
}