VMware Cloud Community
vin01
Expert
Expert
Jump to solution

Correction in vms autodeploy script

I am trying to deploy vms from a csv file as input and with the corresponding roles given in the  csv file.

Need help in avoiding these errors.

1.Write-Progress is not giving progress % (Its just displaying the progress bar)

2.The script is running correctly if I deploy 1st set of vms like(vm1,vm2,vm3) and after completion if I start second set vm4,vm5,vm6 etc.. its failing while Invoke-VMScript with Timeout error while waiting for VMware Tools to start in the guest. Even though I am performing action after vmtools running(line 113 to 116)

3. Even though the supplied credentials are correct.  Its Failed to authenticate with the guest operating system using the supplied credentials while (Invoke-VMScript)

Csv:

pastedImage_3.png

Script:

Write-Host "Enter the required Information when Prompted" -ForegroundColor Yellow

$vcenter = Read-Host "Enter vCenter Name Ex:Sez00vvm**.sweng.ncr.com"

$vcenterCred= Get-Credential -Message "Enter Credentials to Connect vCenter"

Write-Host 'All Required Inputs Received Script is starting VMs Deployment' -ForegroundColor Yellow

Write-Host "Connecting to vCenter $vcenter"

Connect-VIServer $vcenter -Credential $vcenterCred

$inputfile=Import-Csv -Path 'C:\LIBPROJECT\InputFile\answerfilecsv.csv' -UseCulture

$wusclientrolesetup= $inputfile |?{$_.serverroles -contains 'WUS'}

$wsusclientserver=$wusclientrolesetup.VMName + '.' + $wusclientrolesetup.Sitename

$deploytask=@()

if($dnsserver=$inputfile|?{$_.serverroles -contains 'DNS'}){

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $dnsserver.UserName -AdminPassword $dnsserver.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows}

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $dnsserver.IP

$networkspecProperties.SubNetMask = $dnsserver.Subnet

$networkspecProperties.DefaultGateway = $dnsserver.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask+=New-VM -Name $dnsserver.VMName -Template $dnsserver.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask.State){

    Write-Progress -Activity 'Creating VM' -PercentComplete $deploytask.PercentComplete

    $deploytask = Get-Task -Id $deploytask.Id

}

Write-Output "VirualMachine Depolyment Completed with Name "$dnsserver.VMName" from Template $(Get-View -Id $deploytask.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Set-VM -VM $dnsserver.VMName -MemoryGB $dnsserver.Memory -NumCpu $dnsserver.vCpu -Confirm:$false

Get-NetworkAdapter $dnsserver.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $dnsserver.VMName -Confirm:$false

#$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

}

$dnsvm= Get-VM $dnsserver.VMName

while($dnsvm.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$dnsvm.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

$dnsserverinstall= @'

Install-WindowsFeature  DNS -includeManagementTools

Add-DnsServerPrimaryZone -Name $($dnsserver.Sitename) -ZoneFile $($dnsserver.Sitename)

Add-DnsServerPrimaryZone -NetworkId "$($dnsserver.IP.Split('.')[0..2] -join '.').0/24" -ZoneFile $($dnsserver.Sitename)

'@

$dnsserverinstallSub = $ExecutionContext.InvokeCommand.ExpandString($dnsserverinstall)

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $dnsserverinstallSub

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$addRecord = @'

Add-DnsServerResourceRecordA -Name $($dnsrecords.VMName) -IPv4Address $($dnsrecords.IP) -ZoneName $($dnsrecords.Sitename) -CreatePtr

'@

foreach($dnsrecords in $inputfile){

$addRecordSub = $ExecutionContext.InvokeCommand.ExpandString($addRecord)

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $addRecordSub

}

}

foreach($vmsautodeploy in $inputfile|?{$_.serverroles -notcontains 'DNS'}){

$deploytask1=@()

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

if($vmsautodeploy.GuestOSType -eq 'windows'){

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $vmsautodeploy.UserName -AdminPassword $vmsautodeploy.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

    Write-Progress -Activity 'Creating VM' -PercentComplete $deploytask1.PercentComplete

    $deploytask1 = Get-Task -Id $deploytask1.Id

}

Write-Output "VirualMachine Depolyment Completed with Name "$vmsautodeploy.VMName" from Template $(Get-View -Id $deploytask1.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Start-Sleep -Seconds 5

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

#$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 5

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'WUS'){

$wusfeatureinstall=@'

Install-WindowsFeature -Name UpdateServices, UpdateServices-WidDB, UpdateServices-Services, UpdateServices-RSAT, UpdateServices-API, UpdateServices-UI

'@

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wusfeatureinstall

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$wsusdownstreamserversetup= @'

New-Item -Path $env:SystemDrive\WSUS -ItemType Directory -Force

sl "C:\Program Files\Update Services\Tools"

.\wsusutil.exe postinstall CONTENT_DIR=C:\WSUS

`$wsus = Get-WSUSServer

`$wsusConfig =`$wsus.GetConfiguration() 

`$wsusConfig.SyncFromMicrosoftUpdate=`$false 

`$wsusConfig.UpstreamWsusServerName='$($vmsautodeploy.UpStreamWUSServer)'

`$wsusConfig.UpstreamWsusServerPortNumber='$($vmsautodeploy.UpStreamWUSServerPort)'

`$wsusConfig.IsReplicaServer=`$True 

`$wsusConfig.TargetingMode="Client" 

`$wsusConfig.Save() 

`$wsusSub = `$wsus.GetSubscription() 

`$wsusSub.SynchronizeAutomatically=`$True 

`$wsusSub.SynchronizeAutomaticallyTimeOfDay="12:00:00" 

`$wsusSub.NumberOfSynchronizationsPerDay="1"  

`$wsusSub.Save() 

`$wsusSub.StartSynchronization()

'@

$wsusdownstreamserversetupSub = $ExecutionContext.InvokeCommand.ExpandString($wsusdownstreamserversetup)  

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wsusdownstreamserversetupSub

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfigwindows=@'

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 "time00.sweng.ncr.com"

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "time00.sweng.ncr.com"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

#Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $ntpautoconfigwindows

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

elseif($vmsautodeploy.ServerRoles -eq 'FileServer'){

$fileserverfeature=@'

Install-WindowsFeature -Name FS-Resource-Manager, RSAT-FSRM-Mgmt

New-FsrmQuotaTemplate -Name '25GB Volume Usage Limit' -Description 'limit usage to 25GB' -Size 25GB

New-FsrmQuotaTemplate -Name '50GB Volume Usage Limit' -Description 'limit usage to 50GB' -Size 50GB

New-FsrmQuotaTemplate -Name '100GB Volume Usage Limit' -Description 'limit usage to 100GB' -Size 100GB

'@

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $fileserverfeature

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

else{

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

}

else {

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameLinux = ($Chars | Get-Random -Count 9) -join ""

$deploytask1emplinuxSpec = New-OSCustomizationSpec -OSType Linux -Name $RandomNameLinux -Domain 'NCR'  -Type NonPersistent -ErrorAction SilentlyContinue

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameLinux }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

#$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

    Write-Progress -Activity 'Creating VM' -PercentComplete $deploytask1.PercentComplete

    $deploytask1 = Get-Task -Id $deploytask1.Id

}

Write-Output "VirualMachine Depolyment Completed with Name "$vmsautodeploy.VMName" from Template $(Get-View -Id $deploytask1.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false

Start-Sleep -Seconds 3

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vm  | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'Yum Server'){

$yumserverautoconfiglinux=@'

cd /tmp

rpm -ivh vsftpd-3.0.2-22.el7.x86_64.rpm

service vsftpd restart

chkconfig vsftpd on

systemctl start vsftpd.service

systemctl enable vsftpd.service

'@

Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\vsftpd-3.0.2-22.el7.x86_64.rpm' -Destination '/tmp' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $yumserverautoconfiglinux -ScriptType Bash

Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\CentOS7_5x64Bit\' -Destination '/var/ftp/pub/' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfiglinux=@'

'@

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $ntpautoconfiglinux -ScriptType Bash

}

else{

$yumserverIP=$inputfile |?{$_.serverroles -eq 'None'}

$defaultlinuxsettings=@'

cd /etc/yum.repos.d/

rm -rf *

cat <<EOF >  Cent.repo

[$($yumserverIP.IP)]

comment ="CentOS7_5x64Bit"

baseurl=ftp://$($yumserverIP.IP)/pub/CentOS7_5x64Bit

gpgcheck=0

EOF

'@

$defaultlinuxsettingssub=$ExecutionContext.InvokeCommand.ExpandString($defaultlinuxsettings)

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $defaultlinuxsettingssub -ScriptType Bash

}

}

}

Write-Host 'VMS are sucessfully deployed as per the input file' -ForegroundColor Yellow

pastedImage_6.png

Regards Vineeth.K
0 Kudos
22 Replies
vin01
Expert
Expert
Jump to solution

Sorry for the delay.

I have tested on multiple vms which are located in different time zones. Here is the observation

As you said adding the time conversion to EST in script didn't  worked when my local machine (Script Execution VM) is in different time zone.

If my local machine is in EST then the script got executed without any issues(This is expected)

In my main script the error which I got earlier is due to not populating the VM Name and date variables before fetching the vievents (Get-VIEvent -Entity $dnsserver.VMName -Start $now). Its tried to get all the events from the vcenter and in that if it founds guest CustomizationSucceeded then its moving to next line and failing. Thanks for correcting me Sir.

Here is the final version tested on multiple sites and working.

I need few improvements. Can you please help me to complete it.

1. If I mention vcenter name or credentials wrongly the script should not move to next lines just stop and provide a popup like (can not connect to vcenter as vcenter credentials or vcenter name is wrong)

2. In Line 337 I am trying to copy yum repos from script execution machine to the VM but in some environments its taking time to complete the cmd. This is expected due to network.

So my idea is to upload repos folder or iso to datastore ($dst line14) before execution of the script and mount it to the vm when the condition matches at ($vmsautodeploy.ServerRoles -eq 'Yum Server')Next to line 321 and add lines to $yumserverautoconfiglinux (line 322) for mounting the CD rom and copy the repos to (/var/ftp/pub/).

3. On  every role deployment it should write the role has deployed successfully.

Write-Host "Enter the required Information when Prompted" -ForegroundColor Yellow

Add-Type -AssemblyName Microsoft.VisualBasic

$vcenter = [Microsoft.VisualBasic.Interaction]::InputBox("Enter vcenter Name")

$vcenterCred= Get-Credential -Message "Enter Credentials to Connect vCenter"

Write-Host 'All Required Inputs Received Script is starting VMs Deployment' -ForegroundColor Yellow

Write-Host "Connecting to vCenter $vcenter"

Connect-VIServer $vcenter -Credential $vcenterCred

$inputfile=Import-Csv -Path 'C:\LIBPROJECT\InputFile\answerfilecsv.csv' -UseCulture

$wusclientrolesetup= $inputfile |?{$_.serverroles -contains 'WUS'} -ErrorAction SilentlyContinue

$wsusclientserver=$wusclientrolesetup.VMName + '.' + $wusclientrolesetup.Sitename

$deploytask=@()

if($dnsserver=$inputfile|?{$_.serverroles -contains 'DNS'}){

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $dnsserver.UserName -AdminPassword $dnsserver.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows}

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $dnsserver.IP

$networkspecProperties.SubNetMask = $dnsserver.Subnet

$networkspecProperties.DefaultGateway = $dnsserver.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask+=New-VM -Name $dnsserver.VMName -Template $dnsserver.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask.State){

Write-Progress -Activity 'VM Creation' -Status "0%" -PercentComplete $deploytask.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity 'VM Creation' -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask = Get-Task -Id $deploytask.Id 

Write-Progress -Activity 'VM Creation' -Completed

}

Write-Output "VirualMachine Depolyment Completed with Name "$dnsserver.VMName" from Template $(Get-View -Id $deploytask.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Set-VM -VM $dnsserver.VMName -MemoryGB $dnsserver.Memory -NumCpu $dnsserver.vCpu -Confirm:$false

Get-NetworkAdapter $dnsserver.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $dnsserver.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $dnsserver.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $dnsserver.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$dnsvm= Get-VM $dnsserver.VMName

while($dnsvm.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$dnsvm.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

$dnsserverinstall= @'

Install-WindowsFeature  DNS -includeManagementTools

Add-DnsServerPrimaryZone -Name $($dnsserver.Sitename) -ZoneFile $($dnsserver.Sitename)

Add-DnsServerPrimaryZone -NetworkId "$($dnsserver.IP.Split('.')[0..2] -join '.').0/24" -ZoneFile $($dnsserver.Sitename)

'@

$dnsserverinstallSub = $ExecutionContext.InvokeCommand.ExpandString($dnsserverinstall)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $dnsserverinstallSub

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$addRecord = @'

Add-DnsServerResourceRecordA -Name $($dnsrecords.VMName) -IPv4Address $($dnsrecords.IP) -ZoneName $($dnsrecords.Sitename) -CreatePtr

'@

foreach($dnsrecords in $inputfile){

$addRecordSub = $ExecutionContext.InvokeCommand.ExpandString($addRecord)

$guestoperationstatus= Get-VM $dnsserver.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $dnsserver.VMName -GuestUser $dnsserver.UserName -GuestPassword $dnsserver.Password -ScriptType Powershell -ScriptText $addRecordSub

}

}

foreach($vmsautodeploy in $inputfile|?{$_.serverroles -notcontains 'DNS'}){

$deploytask1=@()

$vmhost= (Get-Cluster $dnsserver.Cluster |Get-VMHost |Get-Random|select).name

$dst= (Get-VMHost $vmhost |Get-Datastore 'LIBDatastore').Name

#| Sort-Object -Property FreespaceGB -Descending:$deploytask1rue | Select-Object -First 1

$vmnetwork= (Get-VirtualPortGroup -VMHost $vmhost |?{$_.VLanID -eq $dnsserver.vLANID}).Name

if($vmsautodeploy.GuestOSType -eq 'windows'){

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameWindows = ($Chars | Get-Random -Count 😎 -join ""

$deploytask1empwindowsSpec = New-OSCustomizationSpec -OSType Windows -Name $RandomNameWindows -FullName $vmsautodeploy.UserName -AdminPassword $vmsautodeploy.Password -AutoLogonCount 1  -Workgroup 'NCR' -OrgName 'NCR' -NamingScheme vm -ChangeSid -Type NonPersistent

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameWindows }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

Write-Progress -Activity 'VM Creation' -Status "0%" -PercentComplete $deploytask1.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity 'VM Creation' -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask1 = Get-Task -Id $deploytask1.Id 

Write-Progress -Activity 'VM Creation' -Completed

}

Write-Output "VirualMachine Depolyment Completed with Name "$vmsautodeploy.VMName" from Template $(Get-View -Id $deploytask1.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1empwindowsSpec -Confirm:$false

Start-Sleep -Seconds 5

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 5

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'WUS'){

$wusfeatureinstall=@'

Install-WindowsFeature -Name UpdateServices, UpdateServices-WidDB, UpdateServices-Services, UpdateServices-RSAT, UpdateServices-API, UpdateServices-UI

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wusfeatureinstall

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

$wsusdownstreamserversetup= @'

New-Item -Path $env:SystemDrive\WSUS -ItemType Directory -Force

sl "C:\Program Files\Update Services\Tools"

.\wsusutil.exe postinstall CONTENT_DIR=C:\WSUS

`$wsus = Get-WSUSServer

`$wsusConfig =`$wsus.GetConfiguration() 

`$wsusConfig.SyncFromMicrosoftUpdate=`$false 

`$wsusConfig.UpstreamWsusServerName='$($vmsautodeploy.UpStreamWUSServer)'

`$wsusConfig.UpstreamWsusServerPortNumber='$($vmsautodeploy.UpStreamWUSServerPort)'

`$wsusConfig.IsReplicaServer=`$True 

`$wsusConfig.TargetingMode="Client" 

`$wsusConfig.Save() 

`$wsusSub = `$wsus.GetSubscription() 

`$wsusSub.SynchronizeAutomatically=`$True 

`$wsusSub.SynchronizeAutomaticallyTimeOfDay="12:00:00" 

`$wsusSub.NumberOfSynchronizationsPerDay="1"  

`$wsusSub.Save() 

`$wsusSub.StartSynchronization()

'@

$wsusdownstreamserversetupSub = $ExecutionContext.InvokeCommand.ExpandString($wsusdownstreamserversetup)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $wsusdownstreamserversetupSub

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfigwindows=@'

Push-Location

Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers

Set-ItemProperty . 0 "time00.sweng.ncr.com"

Set-ItemProperty . "(Default)" "0"

Set-Location HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Parameters

Set-ItemProperty . NtpServer "time00.sweng.ncr.com"

Pop-Location

Stop-Service w32time

Start-Service w32time

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

#Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $ntpautoconfigwindows

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

elseif($vmsautodeploy.ServerRoles -eq 'FileServer'){

$fileserverfeature=@'

Install-WindowsFeature -Name FS-Resource-Manager, RSAT-FSRM-Mgmt

New-FsrmQuotaTemplate -Name '25GB Volume Usage Limit' -Description 'limit usage to 25GB' -Size 25GB

New-FsrmQuotaTemplate -Name '50GB Volume Usage Limit' -Description 'limit usage to 50GB' -Size 50GB

New-FsrmQuotaTemplate -Name '100GB Volume Usage Limit' -Description 'limit usage to 100GB' -Size 100GB

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $fileserverfeature

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

else{

$defaultwindowssettings= @'

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUServer" -Value "https://$($wsusclientserver):80"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate" -Name "WUStatusServer" -Value "https://$($wsusclientserver):80"

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallDay" -Value "0"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "ScheduledInstallTime" -Value "3"

Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value "1"

'@

$defaultwindowssettingssub = $ExecutionContext.InvokeCommand.ExpandString($defaultwindowssettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptType Powershell -ScriptText $defaultwindowssettingssub

}

}

else {

$Chars = [Char[]]"abcdefghijklmnopqrstuvwxyz" 

$RandomNameLinux = ($Chars | Get-Random -Count 9) -join ""

$deploytask1emplinuxSpec = New-OSCustomizationSpec -OSType Linux -Name $RandomNameLinux -Domain 'NCR'  -Type NonPersistent -ErrorAction SilentlyContinue

$networkspecProperties = @{OSCustomizationNicMapping= Get-OSCustomizationNicMapping -OSCustomizationSpec $RandomNameLinux }

$networkspecProperties.IpMode = "UseStaticIP"

$networkspecProperties.IpAddress = $vmsautodeploy.IP

$networkspecProperties.SubNetMask = $vmsautodeploy.Subnet

$networkspecProperties.DefaultGateway = $vmsautodeploy.Gateway

#$networkspecProperties.dns = $dnsserver.DNS1,$dnsserver.DNS2

$networkspecProperties.Position = '1'

Set-OSCustomizationNicMapping @networkspecProperties | Out-Null

$deploytask1+=New-VM -Name $vmsautodeploy.VMName -Template $vmsautodeploy.Template -Host $vmhost  -Datastore $dst -DiskStorageFormat Thin  -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false -RunAsync

while('Running','Queued' -contains $deploytask1.State){

Write-Progress -Activity 'VM Creation' -Status "0%" -PercentComplete $deploytask1.PercentComplete

1..10 | ForEach-Object -Process {     

sleep 2

Write-Progress -Activity 'VM Creation' -Status "$($_ * 10)%" -PercentComplete ($_ * 10)  }

$deploytask1 = Get-Task -Id $deploytask1.Id 

Write-Progress -Activity 'VM Creation' -Completed

}

Write-Output "VirualMachine Depolyment Completed with Name "$vmsautodeploy.VMName" from Template $(Get-View -Id $deploytask1.ObjectId -Property Name | select -ExpandProperty Name)" -NoEnumerate

Remove-OSCustomizationSpec -OSCustomizationSpec $deploytask1emplinuxSpec -Confirm:$false

Start-Sleep -Seconds 3

Set-VM -VM $vmsautodeploy.VMName -MemoryGB $vmsautodeploy.Memory -NumCpu $vmsautodeploy.vCpu -Confirm:$false

Get-NetworkAdapter $vmsautodeploy.VMName | Set-NetworkAdapter -NetworkName $vmnetwork -Confirm:$false -StartConnected:$true -ErrorAction SilentlyContinue

Start-VM -VM $vmsautodeploy.VMName -Confirm:$false

$now = Get-Date

$eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

while ($eventTypes -notcontains 'CustomizationSucceeded' -and

  $eventTypes -notcontains 'CustomizationFailed’) {

  Start-Sleep -Seconds 5

  $eventTypes = Get-VIEvent -Entity $vmsautodeploy.VMName -Start $now -MaxSamples ([int]::MaxValue) | % {$_.GetType().Name}

}

$vmsautodeploytoolstatus= Get-VM $vmsautodeploy.VMName

while($vmsautodeploytoolstatus.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsNotRunning"){

Start-Sleep -Seconds 3

$vmsautodeploytoolstatus.ExtensionData.UpdateViewData("Guest.ToolsRunningStatus")

}

if($vmsautodeploy.ServerRoles -eq 'Yum Server'){

$yumserverautoconfiglinux=@'

cd /tmp

rpm -ivh vsftpd-3.0.2-22.el7.x86_64.rpm

service vsftpd restart

chkconfig vsftpd on

systemctl start vsftpd.service

systemctl enable vsftpd.service

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\vsftpd-3.0.2-22.el7.x86_64.rpm' -Destination '/tmp' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $yumserverautoconfiglinux -ScriptType Bash

#Copy-VMGuestFile -VM $vmsautodeploy.VMName -Source 'C:\Prerequisites\Linux\CentOS7_5x64Bit\' -Destination '/var/ftp/pub/' -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -LocalToGuest

}

elseif($vmsautodeploy.ServerRoles -eq 'NTP'){

$ntpautoconfiglinux=@'

'@

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $ntpautoconfiglinux -ScriptType Bash

}

else{

$yumserverIP=$inputfile |?{$_.serverroles -eq 'None'}

$defaultlinuxsettings=@'

cd /etc/yum.repos.d/

rm -rf *

cat <<EOF >  Cent.repo

[$($yumserverIP.IP)]

comment ="CentOS7_5x64Bit"

baseurl=ftp://$($yumserverIP.IP)/pub/CentOS7_5x64Bit

gpgcheck=0

EOF

'@

$defaultlinuxsettingssub=$ExecutionContext.InvokeCommand.ExpandString($defaultlinuxsettings)

$guestoperationstatus= Get-VM $vmsautodeploy.VMName

while($guestoperationstatus.ExtensionData.Guest.GuestOperationsReady -ne "True"){

Start-Sleep -Seconds 3

$guestoperationstatus.ExtensionData.UpdateViewData("Guest.GuestOperationsReady")

}

Invoke-VMScript -VM $vmsautodeploy.VMName -GuestUser $vmsautodeploy.UserName -GuestPassword $vmsautodeploy.Password -ScriptText $defaultlinuxsettingssub -ScriptType Bash

}

}

}

Write-Host '***VMS were sucessfully deployed***' -ForegroundColor Yellow

Regards Vineeth.K
0 Kudos
LucD
Leadership
Leadership
Jump to solution

1. You could do something like this.

Try {

    Connect-VIServer $vcenter -Credential $vcenterCred  -ErrorAction Stop

}

Catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException] {

    $wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

    $wshell.Popup("Incorrect vCenter",0,"vCenter Connection",16) | Out-Null

    return

}

catch {

    $wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop

    $wshell.Popup("Incorrect vCenter credentials",0,"vCenter Connection",16) | Out-Null

    return

}

2. Yes, that should work.
But you could also just copy the folder/files before the network switches.

3. You could something like this, just add the Get-WindowsFeature line at the end of code that installs the feature.

$featureName = 'DNS'

$code = @'

# <== The existing lines go here

Get-WindowsFeature -Name $featureName | Select -ExpandProperty Installed

'@

$codeSub = $ExecutionContext.InvokeCommand.ExpandString($code)

$result = Invoke-VMScript -VM $vm -ScriptText $codeSub -ScriptType Powershell

if($result.ScriptOutput -eq 'True'){

    Write-Host "Feature $featureName installed"

}

else{

    Write-Host "Feature $featureName installation failed"

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vin01
Expert
Expert
Jump to solution

Thank you. I will add in main script and post here for referenc.

Regards Vineeth.K
0 Kudos