티스토리 뷰

#    =======================================================================================================
#    * DESCRIPTION :
#      This script is created to help your job related to 'check vCenter environments' and 'vm creation'. 
#    * 20210701 LGCNS kioeom 
#    =======================================================================================================

# Import VMWARE Module
Import-Module VMware.DeployAutomation
Import-Module VMware.ImageBuilder
Import-Module VMware.VimAutomation.Cis.Core
Import-Module VMware.VimAutomation.Common
Import-Module VMware.VimAutomation.Core
Import-Module VMware.VimAutomation.HA
Import-Module VMware.VimAutomation.License
Import-Module VMware.VimAutomation.Sdk
Import-Module VMware.VimAutomation.Storage
Import-Module VMware.VimAutomation.vds





# Provide vCenter IP 
$vcenter = Read-Host "Enter the IP of your vCenter "
$vmhostcreds = Get-Credential -Message "Please enter the root username and password"

Clear-Host
Write-Host -ForegroundColor Red "`n---- Connecting to vCenter ----"

try{
    Connect-VIServer -server $vcenter -User "$($vmhostcreds.UserName)" -Password ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($vmhostcreds.Password))) -ErrorAction Stop
    Write-Host -ForegroundColor Blue "Successfully connected to vCenter"
    }

catch
    {
    Write-Warning -Message $("Something went wrong connecting to the vCenter. Please read the error message and re-run the script. Error: "+ $_.Exception.Message)
    Break;
    }





# Screen pause Function
Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Red
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

Clear-Host





# Function lists (Menu) 
    function function_lists()
    {
        Write-Host ""
        Write-Host "You may just check the vCenter's environments(1), get the network info for all VMs(2)," -ForegroundColor Magenta
        Write-Host "create a new VM(3), or create multi VMs using csv datafile(4)." -ForegroundColor Magenta
        Write-Host ""
        Write-Host "1. Check whole cluster informations under your vCenter"
        Write-Host "2. Network related INFOs of All VMs"
        Write-Host "3. Create a VM (Please be careful!)" -ForegroundColor Red
        Write-Host "4. Create VMs (using .csv datafile)" -ForegroundColor Red
        Write-Host "0. Leave this program"
        write-host "-------------------------------------------------------------------------------"  
        Write-Host ""
    }





#1. Check Environments
    function check_env()
    {
        Write-Host "** This script gives you lists of "
        Write-Host "`t`t1) CLUSTERs," 
        Write-Host "`t`t2) VMHOSTs, "
        Write-Host "`t`t3) VLANs, "
        Write-Host "`t`t4) VMs, "
        Write-Host "`t`t5) DATASTOREs, "
        Write-Host "`t`t6) TEMPLATEs and"
        Write-Host "`t`t7) OSCustomizationSpec"
        Write-Host "   in sequence."
        Write-Host ""
        Write-Host "I'll Not clear this screen using 'Clear-Host' to backup the on-screen's logs !!"
        Write-Host ""
        pause "Press any key to start!"
        #################################
        Write-Host "1/7) CLUSTERs    under vCenter($($vcenter))" -ForegroundColor Magenta 
        Write-Host ""
        Write-host "Name`t`t HAEnabled`t HAFailoverLevel`t DrsEnabled`t DrsAutomationLevel"
        Write-Host "------------------------------------------------------------------------------------------------" 
        $cluster = get-cluster
        foreach($cl in $cluster){
                Write-host $cl.name,`t,$cl.HAEnabled,`t,$cl.HAFailoverLevel,`t,$cl.DrsEnabled,`t,$cl.DrsAutomationLevel
            }
        Write-Host "End of 1/7 -------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""
        
        #################################
        Write-Host "2/7) VMHOSTs    under each DATACENTER" -ForegroundColor Magenta 
        Write-Host ""
        $dc0 = get-datacenter
        foreach($mydc0 in $dc0){
            $vmhosts = get-vmhost -location $mydc0 | select Name, ConnectionState, PowerState, cputotalmhz, cpuusagemhz, @{Name = 'CpuUsage'; Expression = {($_.CpuUsageMhz / $_.CpuTotalMhz).ToString("P")}}, @{N='memorytotalgb';E={[math]::Round($_.MemoryTotalGB,1)}}, @{N='memoryusagegb';E={[math]::Round($_.MemoryUsageGB,1)}}, @{Name = 'MemoryUsage'; Expression = {($_.MemoryUsageGB / $_.MemoryTotalGB).ToString("P")}}, Version |Sort-Object  name   
            Write-Host ""
            Write-Host "* VMHOSTs : DATACENTER $($mydc0.name) *" -ForegroundColor Magenta 
            Write-Host "---------------------------------------------"
            Write-Host ""
            Write-Host "VMhostName`t ConnState`t PowerState`t cTotal`t cUsed`t c%`t mTotal`t mUsed`t m%`t Version"
            Write-Host "-----------------------------------------------------------------------------------------------------------------------------------" 
            foreach($vmh in $vmhosts){
                Write-Host $vmh.name,`t,$vmh.ConnectionState,`t,$vmh.PowerState,`t,$vmh.cputotalmhz,`t,$vmh.cpuusagemhz,`t,$vmh.CpuUsage,`t,$vmh.memorytotalgb,`t,$vmh.memoryusagegb,`t,$vmh.MemoryUsage,`t,$vmh.Version
            }
        }
        Write-Host "End of 2/7 ----------------------------------------------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""

        #################################
        Write-Host "3/7) VLANs   under each DATACENTER" -ForegroundColor Magenta 
        Write-Host ""
        $vlans = get-cluster | Get-VMHost | Foreach-Object {$strClusterName = $_.Parent.Name; Get-VirtualPortGroup $_ | Select-Object @{N="Cluster";E={$strClusterName}},Name,VLanId}
        Write-Host "Cluster`t Name`t VLanId"
        Write-Host "-------`t ----`t ------"
        foreach($vlan in $vlans){
             Write-Host $vlan.cluster,`t,$vlan.name,`t,$vlan.vlanid    
        }
        Write-Host "End of 3/7 ----------------------------------------------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""
        
        #################################
        Write-Host "4/7) VMs    under each DATACENTER" -ForegroundColor Magenta 
        Write-Host ""
        $dc1 = get-datacenter
        foreach($mydc1 in $dc1){
            $guestos = get-vm -location $mydc1 |select-object name, powerstate, numcpu, memoryGB, vmhost, @{N="vmIP";E={@($_.guest.IPAddress)}} |Sort-Object  vmhost   
            Write-Host ""
            Write-Host "* VMs : DATACENTER $($mydc1.name) *" -ForegroundColor Magenta 
            Write-Host "-----------------------------------------"
            Write-Host ""
            Write-Host "VM name`t Power-state`t CPU-core`t MemoryGB`t VMhostIP`t vmIP"
            Write-Host "---------------------------------------------------------------------------------------------------------------------------------------"  
            foreach($gos in $guestos){
                Write-Host $gos.name,`t,$gos.powerstate,`t,$gos.numcpu,`t,$gos.memoryGB,`t,$gos.vmhost,`t,$gos.vmIP
            }
        }
        Write-Host "End of 4/7 --------------------------------------------------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""


        #################################
        Write-Host "5/7) DATASTOREs    under each DATACENTER" -ForegroundColor Magenta 
        $dc2 = get-datacenter
        foreach($mydc2 in $dc2){
            $datastore = get-datastore -location $mydc2 |select-object datacenter, name, CapacityGB, @{Label=”FreespaceGB”;E={“{0:n2}” -f ($_.FreespaceGB)}}, @{Label="PercentageFree";E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}|Sort-Object Datacenter, name  
            Write-Host ""
            Write-Host "* DATASTOREs : DATACENTER $($mydc2) *" -ForegroundColor Magenta 
            Write-Host "-----------------------------------------------"
            Write-Host ""
            Write-Host "Datacenter`t`t DatastoreName`t Capacity(GB)`t Freespace(GB)`t PercentFree(%)"
            Write-Host "---------------------------------------------------------------------------------------------------------------------------------------" 
            foreach($mystore in $datastore){
                Write-Host $mystore.datacenter,`t,`t,$mystore.name,`t,$mystore.CapacityGB,`t,$mystore.FreeSpaceGB,`t,$mystore.PercentageFree
            }
        }
        Write-Host "End of 5/7 --------------------------------------------------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""

        #################################
        Write-Host "6/7) TEMPLATEs    under each DATACENTER" -ForegroundColor Magenta 
        $dc3 = get-datacenter
        foreach($mydc3 in $dc3){
            $temp = get-template -location $mydc3 |select name, @{N="Host";E={(Get-VMhost -id $_.HostID).Name}}, @{N="Datastore"; E={(Get-Datastore -id $_.DatastoreIDlist).Name -join ","}} | FT -AutoSize 
            Write-Host ""
            Write-Host "* TEMPLATEs : DATACENTER $($mydc3) *" -ForegroundColor Magenta 
            Write-Host "----------------------------------------------"
            Write-Host ""
            $temp
        }
        Write-Host "End of 6/7 --------------------------------------------------------------------------------------------------------------------------------" 
        pause "Press any key to continue..."
        Write-Host ""

        #################################
        Write-Host "7/7) OSCustomizationSpec    under each DATACENTER" -ForegroundColor Magenta 
            $oscs = Get-OSCustomizationSpec |select name, description, type, ostype, lastupdate, server 
            Write-Host ""
            Write-Host "Name`t`t Description Type`t OSType`t  LastUpdate`t Server"
            Write-Host "-----`t`t ----------- ----`t ------`t ----------`t ------"
            foreach($osspc in $oscs){
                Write-Host $osspc.name,`t,$osspc.description,`t,$osspc.type,`t,$osspc.ostype,`t,$osspc.lastupdate`t,$osspc.server
            }
            Write-Host ""
        Write-Host "End of 7/7 --------------------------------------------------------------------------------------------------------------------------------" 
        Write-Host ""
        Write-Host "- Check whole Environments,   Done! -" -ForegroundColor Magenta 
        pause "Press any key to continue..."
        Write-Host ""
    }



#2. Network Info per VM
    function Ninfo()
    {
        Clear-Host
        #Get-View -ViewType VirtualMachine |
        Get-View -ViewType VirtualMachine -PipelineVariable vm |
        Select Name,

               @{N="Datacenter";E={$parentObj = Get-View $_.Parent
               while($parentObj -isnot [VMware.Vim.Datacenter]){
               $parentObj = Get-View $parentObj.Parent}
               $parentObj.Name}},

               @{N='IPAddress';E={$_.Guest.ipAddress}},

               @{N='Gateway';E={($_.Guest.ipstack.iprouteconfig.iproute.gateway.ipaddress | where{$_ -ne $null}) -join '|'}},

               @{N='SubnetMask';E={
               $ipAddr = $_.Guest.ipAddress
               @(($_.Guest.Net.ipconfig.ipaddress | where{$ipAddr -contains $_.IpAddress -and $_.PrefixLength -ne 0}).PrefixLength | %{
               [IPAddress]$ip = 0;
               $ip.Address = (([UInt32]::MaxValue) -shl (32 - $_) -shr (32 - $_))
               $ip.IPAddressToString
               }) -join '|'
               }},

               @{N='DNS';E={[string]::Join(',',($_.Guest.IpStack.DnsConfig.IpAddress))}},

               @{N='MacAddress';E={($_.Config.Hardware.Device | where{$_ -is [VMware.Vim.VirtualEthernetCard]}).MacAddress -join '|'}},

               #@{N='VlanId';E={$folder = Get-Folder VM
               #$folderView = Get-View $folder -Property "[VirtualMachine]ChildEntity.Network.*"
               #$folderView.LinkedView.ChildEntity[0].LinkedView.Network | Select-Object -ExpandProperty Name}},
               @{N='VlanId';E={
               $folder = Get-View -Id $_.Parent -Property "[VirtualMachine]ChildEntity.Network.*"
               ($folder.LinkedView.ChildEntity.where({$vm.MoRef -eq $_.MoRef})).LinkedView.Network.Name}},

               @{N='Network Adapter';E={$_.Config.Hardware.Device  |  Where {$_ -is [VMware.Vim.VirtualEthernetCard]} | ForEach {$_.GetType().Name.Replace('Virtual','')}}} |Out-GridView
        Write-Host ""
        Write-Host "- Network Info (All VMs) listing,   Done! -"  -ForegroundColor Yellow
        pause "Press any key to continue..."
        Write-Host ""
}






#3. Create a new VM
    function new_vm()
    {
        Clear-Host
        Write-Host "** This script let you create a new VM. Follow me."  -ForegroundColor Red
        Write-Host ""
        $vmname = Read-Host "[INPUT] New VM's hostname : "
        $template = Read-Host "[INPUT] Choose the Template : "
        $cpu = Read-Host "[INPUT] New VM's CPU core in count : "
        $mem = Read-Host "[INPUT] New VM's Memory size in GB : "
        Write-Host "[INPUT] New VM's Disk size in GB"
        $dsk = Read-Host "        (In case of Windows OS,  C: will fixed to 70GB) : "
        $dstore = Read-Host "[INPUT] Choose the New VM's Datastore : "
        $vhost = Read-Host "[INPUT] Choose the New VM's VMhost : "
        $oscustomspec = Read-Host "[INPUT] Choose the New VM's OSCustomizationSpec : "
        $ip = Read-Host "[INPUT] New VM's IP Address : "
        $dgw = Read-Host "[INPUT] New VM's Default Gateway : "
        $nwname = Read-Host "[INPUT] Choose the New VM's Network name : "
        

        Write-Host "----------------------------------------- Verify your data. Ctrl+c : Quit the script --------------------------------------------------"
        Write-Host "* VM name : $($vmname)"
        Write-Host "* Template : $($template)"
        Write-Host "* CPU core : $($cpu)"
        Write-Host "* Memory size : $($mem)"
        Write-Host "* Disk size : $($dsk)"
        Write-Host "  (In case of Windows OS,  C: will fixed to 70GB)" -ForegroundColor Magenta 
        Write-Host "* Datastore : $($dstore)"
        Write-Host "* VMhost : $($vhost)"
        Write-Host "* OSCustomizationSpec : $($oscustomspec)"
        Write-Host "* IP : $($ip)"
        Write-Host "* Default GW : $($dgw)"
        Write-Host "* Network name : $($nwname)"
        pause "Press any key to continue..."
        Write-Host ""


        try{
        
        #subnetmask는 변경 필요하면 변수로 추가 또는 요박아넣으세
        $spec = Get-OSCustomizationSpec -Name $oscustomspec
        Get-OSCustomizationNicMapping -OSCustomizationSpec $spec | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $ip -SubnetMask 255.255.255.0 -DefaultGateway $dgw -Dns 1.1.1.1 -Confirm:$false 
        
        New-VM -Name $vmname -VMHost $vhost -Datastore $dstore -DiskStorageFormat Thick -Template $template -OSCustomizationSpec $spec -ErrorAction Stop |
        Set-VM -name $vmname -NumCpu $cpu -MemoryGB $mem -Confirm:$false 
        
        Get-HardDisk -VM $vmname -Name '하드 디스크 2'| Set-HardDisk -CapacityGB $dsk  -Confirm:$False
        
        Get-VM $vmname | Get-NetworkAdapter | Set-NetworkAdapter -Type VMXNet3 -NetworkName $nwname -Confirm:$False -ErrorAction Stop | Out-Null
        
        Write-Host ""
        Write-Host "- Successfully created $($vmname),   Done! -"  -ForegroundColor Yellow
        pause "Press any key to continue..."
        Write-Host ""
        }

        catch{
        Write-Warning -Message $("Something  went wrong in creating the virtual machine: $($vmname). Please read the error message and re-run the script. Error: "+ $_.Exception.Message)
        Break;
        }
    }








#4. Create VMs (using Excel datafile) 
    function create_vms()
    {
        Clear-Host

        Write-Host "-------------------------Data file(name:new-vm_data.csv) need to be at the same directory with this script.  --------------------------------"
        pause "Press any key to go."

        try{


        $list = import-csv "new-vm_data.csv"

        foreach($col in $list)
        {
            $oscustomspec = $col.oscustomspec
        $vmname = $col.vmname
            $vhost = $col.vhost
            $dstore = $col.dstore
            $template = $col.template
            $ip = $col.ip
         $subnet = $col.subnet
            $dgw = $col.gateway
            $nwname = $col.nwname
            $cpu = $col.cpu
            $mem = $col.mem
            $dsk = $col.dsk

        $spec = Get-OSCustomizationSpec -Name $oscustomspec
            Get-OSCustomizationNicMapping -OSCustomizationSpec $spec | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $ip -SubnetMask $subnet -DefaultGateway $dgw -Dns 1.1.1.1 -Confirm:$false 
        
            New-VM -Name $vmname -VMHost $vhost -Datastore $dstore -DiskStorageFormat Thick -Template $template -OSCustomizationSpec $spec -ErrorAction Stop |
            Set-VM -name $vmname -NumCpu $cpu -MemoryGB $mem -Confirm:$false  
        
            Get-HardDisk -VM $vmname -Name '하드 디스크 2'| Set-HardDisk -CapacityGB $dsk  -Confirm:$False
            Get-VM $vmname | Get-NetworkAdapter | Set-NetworkAdapter -Type VMXNet3 -NetworkName $nwname -Confirm:$False -ErrorAction Stop | Out-Null
        }

        Write-Host ""
        Write-Host "- Successfully created $($vmname),   Done! -"  -ForegroundColor Yellow
        pause "Press any key to continue..."
        Write-Host ""
        }

        catch{
        Write-Warning -Message $("Something  went wrong in creating the virtual machine: $($vmname). Please read the error message and re-run the script. Error: "+ $_.Exception.Message)
        Break;
        }
    }








# Function lists action
    function_lists
    $yourchoice = Read-Host -Prompt "Choose one you want." 

    while ("True")
    {
        if ($yourchoice -eq "0") 
        {
            Disconnect-VIServer -Server $vcenter -Confirm:$false; break
        }
        switch -Exact ($yourchoice)
        {
            1 {
                clear-host
                Write-Host ""
                Write-Host "1. Check whole cluster informations under your vCenter"
                write-host "" 
                check_env; 
                write-host "-Done";break
            }
            2 {
                write-host ""
                Write-Host "2. Network related INFOs of All VMs"
                write-host ""
                Ninfo; 
                write-host "-Done";break
            }

            3 {
                write-host ""
                Write-Host "3. Create VM (Please be careful!)" -BackgroundColor Red
                write-host ""
                new_vm; 
                write-host "-Done";break
            }

            4 {
                write-host ""
                Write-Host "4. Create VMs (using .csv datafile)" -BackgroundColor Red
                write-host ""
                create_vms; 
                write-host "-Done";break
            }
 
            Default {write-host "Choose one you want."}
        }

        function_lists
        $yourchoice = Read-Host -Prompt "Choose one you want." 
    }

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함