1 Reply Latest reply on Jul 25, 2018 10:05 PM by LucD

    Looping User input

    RajJon Lurker

      Hello,

      I am trying to create an interactive/automated VM Creation Process. The only thing I think I am missing right now is if I wanted to create more than 1 VM. I would like the User inputs that prompt to enter information to loop in case I wanted to create 2 or more and given an answer to move forward with deployment if finished.

       

      This is a forked version of Altaro's script if anyone is interested. It can be found here.

      https://www.altaro.com/vmware/powercli-script-deploy-vms-and-configure-the-guest-os/

       

       

      # ------vSphere Targeting Variables tracked below------

      $vCenterInstance = "Enter vCenter Here"

      $vCenterUser = "Enter Username Here"

      #Use the following two lines in a standalone script to generate a secure password txt file#

      <# Set and encrypt credentials to file using default method #>

      #$credential = Get-Credential

      #$credential.Password | ConvertFrom-SecureString | Set-Content c:\Temp\LocalPassword.txt

      #---------------------------------------------------------------------------------------------------------------------------------------------

      $vCenterPass = Get-Content C:\Temp\MyEncryptedPassword.txt | ConvertTo-SecureString

      $vCenterCredential = New-Object System.Management.Automation.PSCredential($vCenterUser, $vCenterPass)

      $LocalAdmin = ".\Administrator"

      $LocalPass = Get-Content C:\Temp\LocalPassword.txt | ConvertTo-SecureString

      $LocalCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $LocalAdmin, $LocalPass

      #----------------Interactive Input--------------------------------------------------------------------------

      $VMName1 = Read-Host -Prompt "Please enter in the Hostname for the new Server..."

      $IP = Read-Host -Prompt "Please enter in the IP Address for the new Server..."

      $Subnet = Read-Host -Prompt "Please enter in the Subnet Mask for the new Server..."

      $Gateway = Read-Host -Prompt "Please enter in the Default Gateway for the new Server..."

      #----------------Service Account for Joining Computers to the Domain--------------------------------------------------------------------------

      $JoinNewDomain = '$DomainUser = "Enter Your Domain User";

                        $DomainPWord = ConvertTo-SecureString -String "Enter Password for Domain user" -AsPlainText -Force;

                        $DomainCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $DomainUser, $DomainPWord;

                        Add-Computer -DomainName "Enter in Your Domain Name" -Credential $DomainCredential;

                        Start-Sleep -Seconds 20;

                        Shutdown /r /t 0'

       

       

      # This section logs on to the defined vCenter instance above

      Connect-VIServer $vCenterInstance -Credential $vCenterCredential -WarningAction SilentlyContinue

      ######################################################-User-Definable Variables-In-This-Section-##########################################################################################

      # ------Virtual Machine Targeting Variables tracked below------

      # The Below Variables define the names of the virtual machines upon deployment, the target cluster, and the source template and customization specification inside of vCenter to use during

      # the deployment of the VMs.

      #----------Static Variable Entries---------------------------------------------------------------------------############################################################################

      $SourceVMTemplate = Get-Template -Name "Enter in Template name"

      $SourceCustomSpec = Get-OSCustomizationSpec -Name "Enter in Custom Spec Name"

      $TargetCluster = Get-Cluster -Name "Enter in Cluster name"

      $Datastore = "Enter in Datastore Name"

      # ------This section contains the commands for defining the IP and networking settings for the new virtual machines------

      # NOTE: The below IPs and Interface Names need to be updated for your environment.

      # Domain Controller VM IPs Below

      # NOTE: Insert IP info in IP SubnetMask Gateway Order

      # NOTE: For the purposes of this script we do not define static DNS settings for this single DC VM as it will point to itself for DNS after provisioning of the new domain.

      # You could add an additional netsh line below to assign static DNS settings in the event you need to do so. See the File Server Section below for further details.

      $VM1NetworkSettings = "netsh interface ip set address 'Ethernet0' static $IP $Subnet $Gateway"

      # NOTE: DNS Server IP below should be the same IP as given to the domain controller in the $VM1NetworkSettings Variable

      $VM1DNSSettings1 = 'netsh interface ip set dnsservers name="Ethernet0" static "Enter Primary DNS Address" primary'

      $VM1DNSSettings2 = 'NETSH INTERFACE IP ADD DNS “Ethernet0" "Enter Secondary DNS Address" INDEX=2'

      # ------This Section Sets the Credentials to be used to connect to Guest VMs that are NOT part of a Domain------

      # NOTE - Make sure you input the local credentials for your domain controller virtual machines below. This is used for logins prior to them being promoted to DCs.

      # This should be the same local credentials as defined within the template that you are using for the domain controller VM.

      #########################################################################################################################################################################################

      # Script Execution Occurs from this point down

      # ------This Section Deploys the new VM(s) using a pre-built template and then applies a customization specification to it. It then waits for Provisioning To Finish------

      Write-Verbose -Message "Deploying Virtual Machine with Name: [$VMName1] using Template: [$SourceVMTemplate] and Customization Specification: [$SourceCustomSpec] on Cluster: [$TargetCluster] in Datastore: [$Datastore] and waiting for completion" -Verbose

      New-VM -Name $VMName1 -Template $SourceVMTemplate -ResourcePool $TargetCluster -OSCustomizationSpec $SourceCustomSpec -Datastore $Datastore

      Write-Verbose -Message "Virtual Machine $VMName1 Deployed. Powering On" -Verbose

      Start-VM -VM $VMName1

      # ------This Section Targets and Executes the Scripts on the New Domain Controller Guest VM------

      # We first verify that the guest customization has finished on on the new DC VM by using the below loops to look for the relevant events within vCenter.

      Write-Verbose -Message "Verifying that Customization for VM $VMName1 has started ..." -Verbose

      while($True)

      {

      $VM1Events = Get-VIEvent -Entity $VMName1

      $VM1startedEvent = $VM1Events | Where { $_.GetType().Name -eq "CustomizationStartedEvent" }

      if ($VM1startedEvent)

      {

      break

      }

      else

      {

      Start-Sleep -Seconds 5

      }

      }

      Write-Verbose -Message "Customization of VM $VMName1 has started. Checking for Completed Status......." -Verbose

      while($True)

      {

      $VM1Events = Get-VIEvent -Entity $VMName1

      $VM1SucceededEvent = $VM1Events | Where { $_.GetType().Name -eq "CustomizationSucceeded" }

              $VM1FailureEvent = $VM1Events | Where { $_.GetType().Name -eq "CustomizationFailed" }

      if ($VM1FailureEvent)

      {

      Write-Warning -Message "Customization of VM $VMName1 failed" -Verbose

                  return $False

      }

      if ($VM1SucceededEvent)

      {

                  break

      }

              Start-Sleep -Seconds 5

      }

      Write-Verbose -Message "Customization of VM $VMName1 Completed Successfully!" -Verbose

      # NOTE - The below Sleep command is to help prevent situations where the post customization reboot is delayed slightly causing

      # the Wait-Tools command to think everything is fine and carrying on with the script before all services are ready. Value can be adjusted for your environment.

      Start-Sleep -Seconds 30

      Write-Verbose -Message "Waiting for VM $VMName1 to complete post-customization reboot." -Verbose

      Wait-Tools -VM $VMName1 #-TimeoutSeconds 300

      # NOTE - Another short sleep here to make sure that other services have time to come up after VMware Tools are ready.

      # After Customization Verification is done we change the IP of the VM to the value defined near the top of the script

      Write-Verbose -Message "Getting ready to change IP Settings on VM $VMName1." -Verbose

      Invoke-VMScript -ScriptText $VM1NetworkSettings -VM $VMName1 -GuestCredential $LocalCredential

      Invoke-VMScript -ScriptText {netsh interface ip set dnsservers name = "Ethernet0" static 10.99.0.100 primary} -VM $VMName1 -GuestCredential $LocalCredential

      Invoke-VMScript -ScriptText {NETSH INTERFACE IP ADD DNS “Ethernet0" 10.99.0.101 INDEX=2} -VM $VMName1 -GuestCredential $LocalCredential

      # NOTE - The Below Sleep Command is due to it taking a few seconds for VMware Tools to read the IP Change so that we can return the below output.

      Start-Sleep -Seconds 30

      Invoke-VMScript -ScriptText $JoinNewDomain -VM $VMName1 -GuestCredential $LocalCredential

      # This is strctly informational and can be commented out if needed, but it's helpful when you want to verify that the settings defined above have been

      # applied successfully within the VM. We use the Get-VM command to return the reported IP information from Tools at the Hypervisor Layer.

      Start-Sleep 30

      Invoke-VMScript -ScriptText C:\Config\PowerCLIDeployment.ps1 -VM $VMName1 -Credential $vCenterCredential

      # Then we Actually install the AD Role and configure the new domain

      # End of Script