PowerShellのPowerCLIを使いVMware ESXiの複数のゲストとホストを順次にShutdownしてみる

PowerShell Script

この記事では、ESXiのゲストとホストを順番にシャットダウンする手順をまとめています。PowerShellのスクリプトファイル(.ps1)として作成し、利用することもおすすめです。ぜひご活用ください。

1.WindowsマシンでPowerShellを開きます。

2.PowerShell Galleryをインストールするためには以下のコマンドを実行します。

PS> Install-Module -name PowerShellGet -Force

3.PowerCLIをインストールするためには以下のコマンドを実行します。

PS> Install-Module -Name Vmware.PowerCLI -Scope AllUsers

4.インストールが完了すると、以下のコマンドを実行してPowerCLIが正常にインストールされたか確認できます。

PS> Get-Module -Name VMware*

5.モジュールのコマンドレット一覧を表示するためには以下のコマンドを実行します。

PS> Get-Command -Module VMware.VimAutomation.Core

6.上記5.の表示されたConnect-VIServerコマンドレットを使いESXiサーバへ接続します。

PS> Connect-VIServer -Server <ESXi host ipaddress> -User root -Password ***** -Force
Name                           Port  User
----                           ----  ----
ipaddress                      443   root

7.接続したESXiサーバに登録されているすべてのゲストのPower状態を確認します。

PS> Get-VM | Select-Object ID, Name, PowerState
Id                Name            PowerState
--                ----            ----------
VirtualMachine-5  windows10-00a   PoweredOff
VirtualMachine-6  windows10-00b   PoweredOn

8.PowerがOnであるゲストのみ確認します。

PS> Get-VM | Where-Object { $_.PowerState -eq 'PoweredOn' }  | Select-Object ID, Name, PowerState

9.PoweredOnのゲストのみを選びシャットダウンを実施します。

PS> Get-VM | Where-Object { $_.PowerState -eq 'PoweredOn' } | ForEach-Object { 
       Write-Host $_.name "n秒後シャットダウン開始"
       Start-Sleep -Seconds 3
       Write-Host Stop-VMGuest $_ -Confirm:$false 
       Stop-VMGuest $_ -Confirm:$false 
       if ($?) {
          Write-Host $_.name "シャットダウン正常。"
       } else {
          Write-Host $_.name "シャットダウン失敗。n秒後強制シャットダウン。"
          Start-Sleep -Seconds 10
       Write-Host Stop-VM $_ -Confirm:$false 
          Stop-VM  $_ -Confirm:$false
       }
    }

10.PoweredOnのゲストが0になるまで待ち続けます。

PS> do {
        Start-Sleep -Seconds 10
        #電源ON仮想マシン一覧を表示
        $vms = Get-VM | Where-Object { $_.PowerState -eq 'PoweredOn' }
    } while($vms.Length -gt 0)

11.ESXiホストをシャットダウンします。

PS> Stop-VMHost <ESXi host ipaddress> -Force:$true  -Confirm:$false

12.またはESXiホストへの接続を切ります。

PS> Disconnect-VIServer -Server <ESXi host ipaddress> -Confirm:$false

既に接続が切られている場合、以下のメッセージが表示されます。
Disconnect-VIServer : 2023/07/14 15:06:20 Disconnect-VIServer Could not find VIServer with name ‘<ESXi host ipaddress>’.

タイトルとURLをコピーしました