Guest User

Untitled

a guest
Sep 23rd, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.60 KB | None | 0 0
  1. ####################################################################################################################
  2. #   #
  3. #    SCRIPT NAME        : Handle_VMs.ps1 #
  4. # #
  5. #    DESCRIPTION        : Here are the things that this script can do: #
  6. # 1. Download build for given version, Extract it and delete the compressed files #
  7. # 2. Generate log file #
  8. # 3. Deploy VM with Given IP and downloaded OVF File #
  9. # 4. Force parameter to power off and rename any existing VMs with same IP #
  10. # 5. Generates logs based on Date and deletes older than given limit of days #
  11. # #
  12. #    AUTHOR             : Hiren Barad #
  13. # #
  14. #    CREATION DATE      : 25/08/2018 #
  15. # #
  16. # VERSION : 1.0 # #
  17. #------------------------------------------------------------------------------------------------------------------#
  18. #             R E V I S I O N    H I S T O R Y #
  19. #------------------------------------------------------------------------------------------------------------------#
  20. #     REVISED DATE    :     REVISED BY     :    CHANGE DESCRIPTION #
  21. #------------------------------------------------------------------------------------------------------------------#
  22. # 13/09/2018 Hiren Barad Incorporated Build downloading features #
  23. # #
  24. ####################################################################################################################
  25.  
  26. $Global:BuildLocation = "C:\Users\$env:USERNAME\Downloads\Downloaded Builds\"
  27. $LimitToDeleteLogs = (Get-Date).AddDays(-15)
  28. $logFile = $Global:BuildLocation + "VMDeployment$(Get-Date -f yyyy-MM-dd).log"
  29. [string]$Global:distSite=Distribution site URL if you are downloading your builds from somewhere
  30. [string]$Global:distSiteUsername=Distribution site username if you have authentication in place
  31. [string]$Global:distSitePassword=Distribution site Password if you have authentication in place
  32. [string]$Global:vCenterURL= vCenter URL
  33. [string]$Global:vCenterUsername = vCenter Username and Password
  34. [string]$Global:vCenterPassword = vCenter Password
  35. [bool]$Global:ForceParameter= $false #Keep this as true if you want to poweroff existing VMs and deploy your VM forcefully
  36. [string]$Global:HostName = Hostname where your VM will be deployed
  37. [string]$Global:DataStoreName = Data storename
  38. [string]$Global:ResourcePoolName = Network name
  39.  
  40. #These fields are part of your OVF configuration file and might change from OVF to OVF
  41. [string]$Global:DNS1 =
  42. [string]$Global:DNS2 =
  43. [string]$Global:Gateway =
  44. [string]$Global:NetMask =
  45. [string]$Global:NetworkName =
  46. [string]$Global:RootPassword =
  47.  
  48. ######################################################### Logger ###############################################################
  49.  
  50. Function Set-LogInfo{
  51. Param(
  52. [string]$infostatus,
  53. [string]$topicName,
  54. [string]$info
  55. )
  56. "$infostatus [$((Get-Date).ToString())] $topicName`t: $info" | Out-File $logFile -Append
  57. Write-Host "$infostatus [$(Get-Date -Format "dd-MM-yyyy hh:mm:ss")] $topicName : $info"
  58. }
  59.  
  60. #################################################### Requirements Start #########################################################
  61.  
  62. function copyDependencies{
  63. $PowershellModules = "C:\Users\$env:USERNAME\Documents\WindowsPowerShell\Modules"
  64. $pathToModule = "$PowershellModules\7Zip4Powershell\1.9.0\7Zip4PowerShell.psd1"
  65. if(!$(Test-Path -Path $PowershellModules)){
  66. md "C:\Users\$env:USERNAME\Documents\WindowsPowerShell\Modules"
  67. }
  68.  
  69. $dependencies = Get-ChildItem "$PSScriptRoot\Dependencies" | Select-Object -ExpandProperty Name
  70. $modsinModulesdir = Get-ChildItem $PowershellModules | Select-Object -ExpandProperty Name
  71.  
  72. foreach($a in $dependencies){
  73. if(!($a -in $modsinModulesdir)){
  74. Copy-Item -Path "$PSScriptRoot\Dependencies\$a" $PowershellModules
  75. }
  76. }
  77.  
  78. if(!$(Get-VIToolkitVersion -ErrorAction Ignore)){
  79. Copy-Item -Path "$PSScriptRoot\Dependencies\*" $PowershellModules
  80. }
  81. elseif(-not (Get-Command Expand-7Zip -ErrorAction Ignore)){
  82. Copy-Item -Path "$PSScriptRoot\Dependencies\7Zip4Powershell" $PowershellModules
  83. }
  84.  
  85. if(-not (Get-Command Expand-7Zip -ErrorAction Ignore)){
  86. Import-Module $pathToModule
  87. }
  88. }
  89.  
  90. copyDependencies
  91. #################################################### Requirements End #########################################################
  92.  
  93.  
  94. #################################################### Reusables Start #########################################################
  95.  
  96. Function validatePath{
  97. Param(
  98. [parameter(
  99. Mandatory = $True)]
  100. [string]$Path
  101. )
  102. if(Test-Path -Path $Path)
  103. {
  104. return $True
  105. }else{
  106. return $false
  107. }
  108. }
  109.  
  110. #Validate if given IP is correct or not
  111. Function validateIP{
  112. Param(
  113. [parameter(
  114. Mandatory = $True)]
  115. [string]$IP
  116. )
  117.  
  118. $IPValid = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}"
  119.  
  120. if($IP -match $IPValid){
  121. return $True
  122. }else{
  123. return $false
  124. }
  125. }
  126.  
  127. #extractBuild version from build name
  128. Function extractVersion{
  129. Param(
  130. [parameter(
  131. Mandatory = $True)]
  132. [string]$buildFullName
  133. )
  134.  
  135. $buildName = $buildFullName.Split("-")[1]
  136. $buildName = $buildName -replace '.ovf.tar.gz$',''
  137. return $buildName
  138. }
  139.  
  140. #Check if folder exists or not
  141. Function createFolder{
  142. Param(
  143. [parameter(
  144. Mandatory = $True)]
  145. [string]$folderPath
  146. )
  147.  
  148. if(!(validatePath -Path $folderPath))
  149. {
  150. New-Item -ItemType directory -Path $folderPath
  151. }
  152. }
  153.  
  154. #Delete unnecessary files
  155. Function deleteCompressedFiles{
  156. Param(
  157. [parameter(
  158. Mandatory = $True)]
  159. [string]$folderPath
  160. )
  161.  
  162. del $folderPath/*.gz$
  163. del $folderPath/*.tar$
  164. }
  165.  
  166. #Clear out folder if the size increases more than 5GB
  167. Function manageFolderSize{
  168. Param(
  169. [parameter(
  170. Mandatory = $True)]
  171. [string]$folderPath
  172. )
  173. $Filter = "*.vmdk"
  174. $MaxSize = 5120 #Size in MB
  175. $OldestFile = Get-ChildItem $folderPath -Filter $Filter | Sort LastWriteTime | Select -First 1
  176. $FolderCurrentSize = (Get-ChildItem $folderPath -recurse | Measure-Object -property length -sum).sum / 1MB
  177. if($FolderCurrentSize -GT $MaxSize)
  178. {
  179. Write-output "Deleting File $OldestFile, becuase the Current folder size $FolderCurrentSize MB, has exceeded the maximum size of $MaxSize MB"
  180. Remove-Item $OldestFile.parent.parent.FullName
  181. }
  182. }
  183.  
  184. #################################################### Reusables End #########################################################
  185.  
  186.  
  187. #################################################### Authentication Start #########################################################
  188.  
  189. #This funtion returns valid credentials to access Build distribution website
  190. Function Get-BuildSiteCreds{
  191. Param(
  192. [string]$Username=$Global:distSiteUsername,
  193. [string]$Password = $Global:distSitePassword
  194. )
  195. $PassAsSecureString = ConvertTo-SecureString $Password -AsPlainText -Force
  196. $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$PassAsSecureString
  197. #Set-LogInfo -infostatus "INFO" -topicName "CREDENTIALS" -info "User credentials generated successfully."
  198. return $cred
  199. }
  200.  
  201. Function ConnectToVcenter{
  202. Param(
  203. $URL = $Global:vCenterURL,
  204. [string]$Username=$Global:vCenterUsername,
  205. [string]$Password = $Global:vCenterPassword
  206. )
  207. if(!$($global:DefaultVIServers.count -eq 1)){
  208. try{
  209. $result = Connect-VIServer -Server $URL -User $Username -Password $Password -ErrorAction Stop
  210. if($result){
  211. Set-LogInfo -infostatus "INFO" -topicName "LOGIN" -info "Logged in to $URL"
  212. }}catch{
  213. $ErrorMessage = $_.Exception.Message
  214. Set-LogInfo -infostatus "ERROR" -topicName "LOGIN" -info $ErrorMessage
  215. throw 401
  216. }
  217. }
  218. }
  219.  
  220. #Disconnect from vCenter
  221. Function disconnectFromvCenter{
  222. Set-LogInfo -infostatus "INFO" -topicName "LOGOUT" -info "Signing out from $vCenterURL."
  223. if($global:DefaultVIServers.count -eq 1){
  224. Disconnect-VIServer -confirm:$false -ErrorAction Stop
  225. }
  226. Set-LogInfo -infostatus "INFO" -topicName "LOGOUT" -info "Signed out from $vCenterURL."
  227. }
  228.  
  229. #################################################### Authentication End #########################################################
  230.  
  231. #################################################### Build Download Features Start #########################################################
  232.  
  233. #Check if build is already downloaded in the downloads folder
  234. Function checkBuildalreadyDownloaded{
  235. Param(
  236. [parameter(
  237. Mandatory = $True)]
  238. [string]$buildVersion,
  239. [string]$buildPath
  240. )
  241.  
  242. if(!(Test-Path -Path $buildPath)){
  243. createFolder -folderPath $buildPath
  244. }
  245. $buildName = Get-ChildItem -Path $buildPath | Where-Object { $_.Name -match $buildVersion } | Select-Object -ExpandProperty Name
  246.  
  247. if($buildName){
  248. return $buildName
  249. }
  250.  
  251. return 1
  252. }
  253.  
  254. #This function returns latest build names of given type
  255. Function checkForAvailableBuilds{
  256. Param(
  257. [parameter(
  258. Mandatory = $True)]
  259. [string]$version="",
  260. [string]$distributionSite=$Global:distSite,
  261. [string]$distributionSiteUsername = $Global:distSiteUsername,
  262. [string]$distributionSitePassword = $Global:distSitePassword
  263. )
  264. try{
  265.  
  266. #Defining Distribution Portal url and getting credentials
  267. $URL = $distributionSite
  268. $creds = Get-BuildSiteCreds -Username $distributionSiteUsername -Password $distributionSitePassword
  269. $buildName = @()
  270. #Fetching the URL to download links with given type
  271. $type = ".ovf.tar.gz"
  272.  
  273. if($version -ne ""){
  274. $links = (Invoke-WebRequest -Uri $URL -Credential $creds).Links | Where href -Like "*$type" | Where href -Like "*$version*" | Select-Object -ExpandProperty href
  275. }else{
  276. $links = (Invoke-WebRequest -Uri $URL -Credential $creds).Links | Where href -Like "*$type" | Select-Object -ExpandProperty href
  277. }
  278. $filestoGet = $links.Count
  279. if($filestoGet -eq 1){
  280. $buildName = $links.split("/")[1]
  281. }
  282. else{
  283. while($filestoGet -gt 0)
  284. {
  285. $link = $links[$filestoGet-1]
  286. $link = $link.split("/")[1]
  287. $buildName += $link
  288. $filestoGet -= 1
  289. }
  290. }
  291. if($buildName.Count -gt 1){
  292. Write-Host "Found multiple builds with same version please select which build to Download:"
  293. $i=0
  294. foreach($name in $buildName){
  295. Write-Host "$($i+1). $name"
  296. $i += 1
  297. }
  298. $correctInput= $false
  299. while(!$correctInput){
  300. try{
  301. [int]$userschoice = Read-Host -Prompt "Please enter a valid number from above:"
  302. if($userschoice -le 0 -or $userschoice -gt $buildName.Count)
  303. {
  304. $correctInput = $false
  305. }else{
  306. $correctInput = $true
  307. }
  308. }catch{
  309. $correctInput = $false
  310. }
  311. }
  312. $buildName = $buildName[$userschoice-1]
  313. }else{
  314. $buildName = $buildName
  315. }
  316.  
  317. return $buildName
  318. }catch{
  319. $ErrorMessage = $_.Exception.Message
  320. $FailedItem = $_.Exception.ItemName
  321. Set-LogInfo -infostatus "ERROR" -topicName "QUERY BUILDS" -info "No builds found with that type"
  322. }
  323.  
  324. }
  325.  
  326. #Download given build
  327. Function downloadBuild{
  328. Param(
  329. [parameter(
  330. Mandatory = $True)]
  331. [string]$buildName,
  332. [string]$downloadPath=$Global:BuildLocation
  333. )
  334. try{
  335. $URL = $Global:distSite
  336. $creds = Get-BuildSiteCreds -Username $Global:distSiteUsername -Password $Global:distSitePassword
  337. #Fetching the URL to download links with given type
  338. Set-LogInfo -infostatus "INFO" -topicName "BUILD DOWNLOAD" -info "Figuring out the requested build type."
  339.  
  340. $link = (Invoke-WebRequest -Uri $URL -Credential $creds).Links | Where href -Like "*$buildName*" | Select-Object -ExpandProperty href
  341. $file = $link.split("/")[1]
  342. $link = $URL + $link
  343. Set-LogInfo -infostatus "INFO" -topicName "BUILD DOWNLOAD" -info "Build with name $buildName found successfully."
  344.  
  345. Set-LogInfo -infostatus "INFO" -topicName "BUILD INFO" -info "Downloading build with name $buildName............."
  346.  
  347. Invoke-WebRequest -Uri $link -Credential $creds -OutFile $downloadPath/$file
  348. Set-LogInfo -infostatus "INFO" -topicName "BUILD DOWNLOAD" -info "Build $buildName downloaded successfully."
  349. }catch{
  350. $ErrorMessage = $_.Exception.Message
  351. $FailedItem = $_.Exception.ItemName
  352. Set-LogInfo -infostatus "ERROR" -topicName "BUILD DOWNLOAD" -info $ErrorMessage
  353. Set-LogInfo -infostatus "ERROR" -topicName "BUILD DOWNLOAD" -info $FailedItem
  354. }
  355. }
  356.  
  357. #Extract from GZ compression
  358. Function DeGZip-File{
  359. Param(
  360. $infile,
  361. $outfile = ($infile -replace '\.gz$','')
  362. )
  363.  
  364. $input = New-Object System.IO.FileStream $infile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)
  365. $output = New-Object System.IO.FileStream $outfile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
  366. $gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)
  367.  
  368. $buffer = New-Object byte[](1024)
  369. while($true){
  370. $read = $gzipstream.Read($buffer, 0, 1024)
  371. if ($read -le 0){break}
  372. $output.Write($buffer, 0, $read)
  373. }
  374.  
  375. $gzipStream.Close()
  376. $output.Close()
  377. $input.Close()
  378. }
  379.  
  380. #Extract TAR File
  381. Function Expand-Tar{
  382. Param(
  383. $infile,
  384. $outfile = ($infile -replace '\.tar$','')
  385. )
  386. if (-not (Get-Command Expand-7Zip -ErrorAction Ignore))
  387. {
  388. copyDependencies
  389. }
  390.  
  391. Expand-7Zip $infile $outfile
  392. deleteCompressedFiles -folderPath $Global:BuildLocation
  393. }
  394.  
  395.  
  396. #################################################### Build Download Features End #########################################################
  397.  
  398. #################################################### VM Deployment Features Start #########################################################
  399.  
  400. #return OVF File Path
  401. Function Get-OVFPath{
  402. Param(
  403. [parameter(
  404. Mandatory = $True)]
  405. [string]$buildVersion,
  406. [string]$buildPath
  407. )
  408.  
  409. $buildVersionParts = $buildVersion.Split(".")
  410. $newBuildVersion = $buildVersionParts[0] + $buildVersionParts[1] + "." + $buildVersionParts[2] + $buildVersionParts[3]
  411. $OVFPATH = get-childitem $buildPath -recurse -File | where {$_.extension -eq ".ovf"} | where {$_.Name -like "*$newBuildVersion*" } | %{$_.FullName}
  412.  
  413. return $OVFPATH
  414. }
  415.  
  416. Function Get-MFPath{
  417. Param(
  418. [parameter(
  419. Mandatory = $True)]
  420. [string]$buildVersion,
  421. [string]$buildPath
  422. )
  423. $buildVersionParts = $buildVersion.Split(".")
  424. $newBuildVersion = $buildVersionParts[0] + $buildVersionParts[1] + "." + $buildVersionParts[2] + $buildVersionParts[3]
  425.  
  426. $MFPATH = get-childitem $buildPath -recurse -File | where {$_.extension -eq ".mf"} | where {$_.Name -like "*$newBuildVersion*" } | %{$_.FullName}
  427.  
  428. return $MFPATH
  429. }
  430.  
  431. Function Get-VMDKPath{
  432. Param(
  433. [parameter(
  434. Mandatory = $True)]
  435. [string]$buildVersion,
  436. [string]$buildPath
  437. )
  438. $buildVersionParts = $buildVersion.Split(".")
  439. $newBuildVersion = $buildVersionParts[0] + $buildVersionParts[1] + "." + $buildVersionParts[2] + $buildVersionParts[3]
  440. $VMDKPATH = get-childitem $buildPath -recurse -File | where {$_.extension -eq ".vmdk"} | where {$_.Name -like "*$newBuildVersion*" } | %{$_.FullName}
  441. return $VMDKPATH
  442. }
  443.  
  444. #Validate build integrity with MF file
  445. Function buildIntegrityCheck{
  446. Param(
  447. [parameter(
  448. Mandatory = $True)]
  449. [string]$MFFilePath,
  450. [parameter(
  451. Mandatory = $True)]
  452. [string]$OVFFilePath,
  453. [parameter(
  454. Mandatory = $True)]
  455. [string]$VMDKFilePath
  456. )
  457.  
  458. if(($MFFilePath -eq '') -or ($OVFFilePath -eq '') -or ($VMDKFilePath -eq ''))
  459. {
  460. throw "Could not get Build files. Make sure your build folder has the build files(OVF, VMDK and MF.)"
  461. }
  462.  
  463. $OVFFileHash = Get-FileHash -Algorithm SHA1 -Path $OVFFilePath | Select-Object -ExpandProperty Hash
  464. $VMDKFileHash = Get-FileHash -Algorithm SHA1 -Path $VMDKFilePath | Select-Object -ExpandProperty Hash
  465. $MFContent = Get-Content $MFFilePath
  466. $actualOVFHash = $MFContent.split("\n")[0].Split("=")[1].Trim()
  467. $actualVMDKHash = $MFContent.split("\n")[1].Split("=")[1].Trim()
  468. echo $OVFFileHash.ToLower()
  469. if(($actualOVFHash -contains $OVFFileHash.ToLower()) -and ($actualVMDKHash -contains $VMDKFileHash.ToLower())){
  470. return $True
  471. }
  472. return $false
  473. }
  474.  
  475.  
  476. #Check if VM exist with This IP
  477. Function CheckVMwithIP{
  478. Param(
  479. [string]$vmIP
  480. )
  481. ConnectToVcenter
  482. Set-LogInfo -infostatus "INFO" -topicName "FINDINGVM" -info "Searching for VMs with IP: $vmIP"
  483. $view = @(Get-View -ViewType VirtualMachine | ?{ $_.Guest.IPAddress -eq $vmIP })
  484. $vmNamesFound = @()
  485. if($view.Count -gt 1){
  486. Set-LogInfo -infostatus "INFO" -topicName "FINDINGVM" -info "Found multiple VMs with IP: $vmIP"
  487. foreach($vm in $view){
  488. #Printing results
  489. $vmName = $vm.Name
  490. Set-LogInfo -infostatus "INFO" -topicName "FINDINGVM" -info "Found VM $vmName with IP: $vmIP"
  491. $vmNamesFound += $vmName
  492. }
  493. return $vmNamesFound
  494. }elseif($view.Count -eq 1){
  495. $vmName = $view[0].Name
  496. Set-LogInfo -infostatus "INFO" -topicName "FINDINGVM" -info "Found VM $vmName with IP: $vmIP"
  497. return $vmName
  498. }else{
  499. Set-LogInfo -infostatus "INFO" -topicName "FINDINGVM" -info "No VM found with IP: $vmIP"
  500. return ""
  501. }
  502. disconnectFromvCenter
  503. }
  504.  
  505. #Check VM STATUS
  506.  
  507. Function checkRunStatusOfVM{
  508. Param(
  509. [VMware.VimAutomation.ViCore.Impl.V1.VM.UniversalVirtualMachineImpl] $VM
  510. )
  511. if($VM.PowerState -eq "PoweredOn"){
  512. return 10
  513. }else{
  514. return 0
  515. }
  516.  
  517. }
  518.  
  519. #Generate VM Name
  520.  
  521. Function GenerateVMName{
  522. Param(
  523. [Parameter(Mandatory=$true)]
  524. [String]$FilePath="1",
  525. [String]$VMIP="1"
  526. )
  527.  
  528.  
  529. if($FilePath -eq 1 -or $VMIP -eq 1){
  530. Set-LogInfo -infostatus "ERROR" -topicName "VMNAME" -info "VM IP or Filepath for the OVF not given correctly."
  531. Exit
  532. }
  533. Set-LogInfo -infostatus "INFO" -topicName "VMNAME" -info "Generating VM name........"
  534. $filename = [io.path]::GetFileNameWithoutExtension($FilePath)
  535. $ipParts = @()
  536. $ipParts = $VMIP.Split(".")
  537. $first = $ipParts[2]
  538. $second = $ipParts[3]
  539. $vmName = "$first`_$second`_$filename"
  540.  
  541. Set-LogInfo -infostatus "INFO" -topicName "VMNAME" -info "VM Name will be $vmName"
  542. return $vmName
  543. }
  544.  
  545.  
  546. #Power Off VM
  547.  
  548.  
  549. Function PowerOff{
  550. Param(
  551. [string]$VMName
  552. )
  553. try{
  554. ConnectToVcenter
  555. $VMtoPowerOff = Get-VM -Name $VMName
  556. Set-LogInfo -infostatus "INFO" -topicName "POWEROFF" -info "Powering off VM $VMName"
  557. Stop-VM -VM $VMtoPowerOff -Confirm:$false
  558. Set-LogInfo -infostatus "INFO" -topicName "POWEROFF" -info "VM $VMName powered off successfully."
  559. disconnectFromvCenter
  560. }catch{
  561. $ErrorMessage = $_.Exception.Message
  562. Set-LogInfo -infostatus "ERROR" -topicName "POWEROFF" -info "Unable to poweroff VM with name $VMName"
  563. Set-LogInfo -infostatus "ERROR" -topicName "POWEROFF" -info $ErrorMessage
  564. disconnectFromvCenter
  565. throw 404
  566. }
  567.  
  568. }
  569.  
  570.  
  571. #Rename a VM
  572.  
  573. Function renameVM{
  574. Param(
  575. [string]$oldName,
  576. [string]$newName,
  577. [bool]$Force
  578. )
  579. try{
  580. #Random number Generator
  581. ConnectToVcenter
  582. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Checking if VM with $newName already exists...."
  583.  
  584. $newVM = Get-VM -Name $newName -ErrorAction Ignore
  585.  
  586. while($newVM -or $oldName -like "DELETE*"){
  587. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "VM $newName is already there."
  588. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Generating a new Random name for VM to delete."
  589. $randomNumber = Get-Random -Maximum 100
  590. $newName = "$newName`_$randomNumber"
  591. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Setting VM name to $newName."
  592. try{
  593. $newVM = Get-VM -Name $newName -ErrorAction Stop
  594. }catch{
  595. Break
  596. }
  597. }
  598. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Getting the VM with name $oldName"
  599. $VMtoRename = Get-VM -Name $OldName
  600.  
  601. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Checking power status of VM $oldName"
  602. $status = checkRunStatusOfVM -VM $VMtoRename
  603.  
  604. if($status -eq 0){
  605. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "VM $oldName is already Powered Off."
  606. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Renaming VM $oldName to $newName."
  607.  
  608. Set-VM -VM $VMtoRename -Name $newName -Confirm:$false
  609.  
  610. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Renaming VM $oldName to $newName Successfull."
  611. }elseif($status -eq 10 -and $Force){
  612. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "VM $oldName is powered On."
  613. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Renaming VM Forcefully....."
  614.  
  615. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Powering off VM $oldName"
  616. Stop-VM $VMtoRename -Confirm:$false
  617. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "VM $oldName powered off successfully."
  618.  
  619. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Renaming VM $oldName to $newName."
  620. Set-VM -VM $VMtoRename -Name $newName -Confirm:$false
  621. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "Renaming VM $oldName to $newName successfull."
  622. }else{
  623. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "VM $oldName is powered On."
  624. Set-LogInfo -infostatus "INFO" -topicName "RENAME" -info "If you want to continue run the script with Force parameter as True."
  625. disconnectFromvCenter
  626. throw 401
  627. }
  628. disconnectFromvCenter
  629.  
  630. }catch{
  631. if($_.toString() -eq 401){
  632. Set-LogInfo -infostatus "ERROR" -topicName "RENAME" -info "Error code 10 thrown."
  633. Set-LogInfo -infostatus "ERROR" -topicName "RENAME" -info "VM with name $oldName is in Powered On state."
  634. #Exit
  635. disconnectFromvCenter
  636. throw 401
  637. }else{
  638. $ErrorMessage = $_.Exception.Message
  639. Set-LogInfo -infostatus "ERROR" -topicName "RENAME" -info $ErrorMessage}
  640. disconnectFromvCenter
  641. }
  642.  
  643. }
  644.  
  645.  
  646. #################################################### VM Deployment Features END #########################################################
  647.  
  648.  
  649. #Download requested version and extract the files
  650. Function downloadVersion{
  651. Param(
  652. [parameter(
  653. Mandatory = $True)]
  654. [string]$buildVersion,
  655. $buildPath=$Global:BuildLocation
  656. )
  657. manageFolderSize -folderPath $buildV
  658. createFolder -folderPath $buildPath
  659. $buildName = checkForAvailableBuilds -version $buildVersion
  660. $buildVersion = extractVersion -buildFullName $buildName
  661. $buildexists = checkBuildalreadyDownloaded -buildVersion $buildVersion -buildPath $buildPath
  662.  
  663. if($buildexists.Count -ne 1){
  664. throw "Please, delete any existing files with same version number from the destination folder. Keep only one file with given version name."
  665. }
  666.  
  667. if($buildexists -eq 1){
  668. downloadBuild -buildName $buildName -downloadPath $buildPath
  669.  
  670. DeGZip-File -infile "$buildPath$buildName"
  671. $tarFile = $buildexists -replace '.gz$',''
  672. Expand-Tar "$buildPath$tarFile"
  673. }elseif($buildexists -match ".tar.gz$"){
  674. DeGZip-File -infile "$buildPath$buildexists"
  675. $tarFile = $buildexists -replace '.gz$',''
  676. Expand-Tar "$buildPath$tarFile"
  677. }elseif($buildexists -match ".tar$"){
  678. Expand-Tar "$buildPath$buildexists"
  679. }
  680.  
  681. $OVFFile = Get-OVFPath -buildVersion $buildVersion -buildPath $buildPath
  682. $MFFile = Get-MFPath -buildVersion $buildVersion -buildPath $buildPath
  683. $VMDKFile = Get-VMDKPath -buildVersion $buildVersion -buildPath $buildPath
  684.  
  685. if(!(buildIntegrityCheck -MFFilePath $MFFile -OVFFilePath $OVFFile -VMDKFilePath $VMDKFile)){
  686. throw "Build integrity not correct. Redownload the build and try again."
  687. }else{
  688. return $OVFFile
  689. }
  690. }
  691.  
  692.  
  693.  
  694. Function deploy-VM{
  695. Param(
  696. [parameter(
  697. Mandatory = $True)]
  698. [string]$ip,
  699. [parameter(
  700. Mandatory = $True)]
  701. [string]$OVFPath,
  702. [string]$vCenterURL=$Global:vCenterURL,
  703. [string]$vCenterUsername = $Global:vCenterUsername,
  704. [string]$vCenterPassword = $Global:vCenterPassword,
  705. [bool]$ForceParameter= $false,
  706. [string]$HostName = $Global:HostName,
  707. [string]$DataStoreName = $Global:DataStoreName,
  708. [string]$ResourcePoolName = $Global:ResourcePoolName,
  709. [string]$DNS1 = $Global:DNS1,
  710. [string]$DNS2 = $Global:DNS2,
  711. [string]$Gateway = $Global:Gateway,
  712. [string]$NetMask = $Global:NetMask,
  713. [string]$NetworkName = $Global:NetworkName,
  714. [string]$RootPassword = $Global:RootPassword
  715. )
  716. if(!(validateIP -IP $ip)){
  717. throw "Please enter a valid IP address."
  718. }
  719. try{
  720. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Getting OVF Configuration....."
  721. try{
  722. ConnectToVcenter -Username $vCenterUsername -Password $vCenterPassword -URL $vCenterURL
  723. $OVFConfig = Get-OvfConfiguration $OVFPath -ErrorAction Stop
  724.  
  725.  
  726. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Finding $HostName....."
  727. $VMHost = Get-VMHost -Name $HostName -ErrorAction Stop
  728.  
  729. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Finding $DataStoreName....."
  730. $DataStore = $VMHost | Get-Datastore -Name $DataStoreName -ErrorAction Stop
  731.  
  732. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Finding $ResourcePoolName....."
  733. $resourcePool = Get-ResourcePool -Name $ResourcePoolName -ErrorAction Stop
  734.  
  735. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Checking $NetworkName....."
  736. $bridgedNetwork = Get-VirtualPortGroup -VMHost $VMHost | where {$_.Name -eq $NetworkName} -ErrorAction Stop
  737.  
  738. }catch{
  739. Set-LogInfo -infostatus "ERROR" -topicName "INTIALIZING" -info "Could not find this resource. Compare the config file data with portal to correct."
  740. throw $_
  741. }
  742.  
  743. $VMName = GenerateVMName -FilePath $OVFPath -VMIP $ip
  744.  
  745. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Checking if VM with $VMName name already exist....."
  746. try{
  747. $VM = Get-VM -Name $VMName -ErrorAction Stop
  748. }catch{
  749. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "No VM found with $VMName name."
  750. }
  751.  
  752. #Checking if VM with same name or IP exists.
  753. if($VM){
  754. renameVM -oldName $VMName -newName "DELETE_$VMName" -Force $ForceParameter
  755. }
  756.  
  757. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "Checking if VM with IP $VM_IP already exist....."
  758. $VM1 = CheckVMwithIP -vmIP $ip
  759.  
  760. if($VM1){
  761. foreach($vmfound in $VM1){
  762. if($vmfound -like "*DELETE_*"){
  763. renameVM -oldName $vmfound -newName "$vmfound" -Force $ForceParameter
  764. }else{
  765. renameVM -oldName $vmfound -newName "DELETE_$vmfound" -Force $ForceParameter
  766. }
  767. }
  768. }else{
  769. Set-LogInfo -infostatus "INFO" -topicName "INTIALIZING" -info "No VM found with IP $VM_IP."
  770. }
  771.  
  772. #Setting up VM
  773. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting OVF Configuration....."
  774.  
  775. #EVERYTHING BELOW THIS YOU WILL NEED TO CONFIGURE BASED ON YOUR OVF FILE
  776.  
  777. # IP Address
  778. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting IP Address $VM_IP"
  779. $OVFConfig.<will change as per your OVF config object> = $ip
  780.  
  781. # Gateway
  782. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting Gateway $GW"
  783. $OVFConfig.<will change as per your OVF config object> = $Gateway
  784.  
  785. # Netmask
  786. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting NetMask $netMask"
  787. $OVFConfig.<will change as per your OVF config object> = $NetMask
  788.  
  789. # DNS1
  790. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting First DNS Server $DNS1"
  791. $OVFConfig.<will change as per your OVF config object> = $DNS1
  792.  
  793. # DNS2
  794. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting Second DNS Server Address $DNS2"
  795. $OVFConfig.<will change as per your OVF config object> = $DNS2
  796.  
  797. # HostName
  798. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting Hostname Value : $HostName"
  799. $OVFConfig.<will change as per your OVF config object> = $VMHost.Name
  800.  
  801. #Bridged Network Binding
  802. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting Bridged Network as : $NetworkName"
  803. $OVFConfig.<will change as per your OVF config object> = $bridgedNetwork
  804.  
  805. #Root Password
  806. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Setting root Password as : $RootPassword"
  807. $OVFConfig.<will change as per your OVF config object> = $RootPassword
  808.  
  809. #Deploying the VM
  810. ConnectToVcenter -Username $vCenterUsername -Password $vCenterPassword -URL $vCenterURL
  811. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Starting deployment of $VMName....."
  812. try{
  813. Import-VApp -Source $OVFPath -OvfConfiguration $OVFConfig -Name $VMName -Location $resourcePool -VMHost $VMHost -Datastore $DataStore -Confirm:$false -ErrorAction Stop
  814. }catch{
  815. Set-LogInfo -infostatus "ERROR" -topicName "DEPLOYMENT" -info "An error occured while deploying $VMName"
  816. throw $_
  817. }
  818.  
  819. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Deployment complete of $VMName."
  820.  
  821. #Starting the VM
  822.  
  823. $DeployedVM = Get-VM -Name $VMName
  824. Set-LogInfo -infostatus "INFO" -topicName "START VM" -info "Starting $VMName......"
  825. try{
  826. Start-VM -VM $DeployedVM -Confirm:$false -ErrorAction Stop
  827. }catch{
  828. Set-LogInfo -infostatus "ERROR" -topicName "START VM" -info "An error occured while starting $VMName"
  829. throw $_
  830. }
  831. Set-LogInfo -infostatus "INFO" -topicName "INITIALIZING" -info "Started $VMName successfully."
  832. return $VMName
  833. }catch{
  834. if($_.toString() -eq 401){
  835. Set-LogInfo -infostatus "ERROR" -topicName "DEPLOYMENT" -info "You are unauthorized to perform this operation. Please check log for more details."
  836. }elseif($_.toString() -eq 404)
  837. {
  838. Set-LogInfo -infostatus "ERROR" -topicName "DEPLOYMENT" -info "Could not find correct resource to perform the operation. Refer preceding steps for more info."
  839. }elseif($_.toString() -eq 406){
  840. Set-LogInfo -infostatus "ERROR" -topicName "DEPLOYMENT" -info "Requesting with invalid data. Correct the config file and Run the script."
  841. }elseif($_.toString() -eq 201){
  842. Set-LogInfo -infostatus "INFO" -topicName "DEPLOYMENT" -info "Created basic folders. Please enter the required data in config file and Run the script."
  843. }
  844. $ErrorMessage = $_.Exception.Message
  845. Set-LogInfo -infostatus "ERROR" -topicName "DEPLOYMENT" -info $ErrorMessage
  846. }finally{
  847.  
  848. if($global:DefaultVIServers.count -eq 1){
  849. Set-LogInfo -infostatus "INFO" -topicName "FINISHING UP" -info "Disconnecting from vCenter."
  850. disconnectFromvCenter
  851. Set-LogInfo -infostatus "INFO" -topicName "FINISHING UP" -info "Disconnected from vCenter."
  852. }
  853. Set-LogInfo -info ""
  854. }
  855. }
  856.  
  857.  
  858. Function start-Deployment{
  859. Param(
  860. [parameter(
  861. Mandatory = $True)]
  862. [string]$ip,
  863. [parameter(
  864. Mandatory = $True)]
  865. [string]$buildVersion,
  866. [string]$downloadPath=$Global:BuildLocation,
  867. [bool]$forceParameter=$false
  868. )
  869. $Global:BuildLocation = $downloadPath
  870. # Delete files older than the $limit.
  871. Get-ChildItem -Path $Global:BuildLocation -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $LimitToDeleteLogs } | Remove-Item -Force
  872.  
  873. $OVFFile = downloadVersion -buildVersion $buildVersion -buildPath $downloadPath
  874.  
  875. $VMName = deploy-VM -ip $ip -OVFPath $OVFFile -ForceParameter $forceParameter
  876. }
Add Comment
Please, Sign In to add comment