Skip to content

Instantly share code, notes, and snippets.

@gowatana
Created July 30, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gowatana/46c51a7fead500a29a14e0e2e8c8d144 to your computer and use it in GitHub Desktop.
Save gowatana/46c51a7fead500a29a14e0e2e8c8d144 to your computer and use it in GitHub Desktop.
# Cleanup VMs
# Usage:
# PowerCLI> ./cleanup_list_vm.ps1 <VM_List.txt>
$vm_list_file = $args[0]
if($vm_list_file.Length -lt 1){"リストを指定して下さい。"; exit}
if((Test-Path $vm_list_file) -ne $true){"リストが見つかりません。"; exit}
$vm_name_list = gc $vm_list_file |
where {$_ -notmatch "^$|^#"} | Sort-Object | select -Unique
function step_mark {
param (
[String]$step_no,
[String]$step_message
)
""
"=" * 60
"Step $step_no $step_message"
""
}
$vms = Get-VM | sort Name
$delete_vms = @()
$vms | % {
$vm = $_
if($vm_name_list -notcontains $vm.Name){
$delete_vms += $vm
}
}
step_mark 1 "削除VM一覧"
$delete_vms | ft -AutoSize Name,PowerState,Folder,ResourcePool
$check = Read-Host "上記のVMを削除しますか? yes/No"
if($check -ne "yes"){"削除せず終了します。"; exit}
step_mark 2 "VM削除"
$delete_vms | % {
$vm = $_
if($vm.PowerState -eq "PoweredOn"){
"Stop VM:" + $vm.Name
$vm = $vm | Stop-VM -Confirm:$false
}
"Delete VM:" + $vm.Name
$vm | Remove-VM -DeletePermanently -Confirm:$false
}
@gowatana
Copy link
Author

下記の投稿むけ。

PowerCLI で不要 VM を一括削除してみる。
https://communities.vmware.com/people/gowatana/blog/2018/07/30/powercli-vm-delete

あらかじめ、削除禁止VM名を羅列したリストファイルを用意しておく。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment