Hi to all,
I need get UUID Disk with powercli, is that possible?
Regards
Hi to all,
I need get UUID Disk with powercli, is that possible?
Regards
Below is the commandline I use to deploy a VM from a template...
New-VM -Name 'TestDeploy' -Template 'win2016x64' -Datastore 'superdoooperfast_ssd' -DiskStorageFormat Thin -Location (Get-Cluster -Name 'yomama' | Get-Datacenter | Get-Folder -Name 'Discovered virtual machine') -ResourcePool 'yomama'
That above works great. Now I need it to use a customization called 'win2016x64'.....
New-VM -Name 'TestDeploy' -Template 'win2016x64' -Datastore 'superdoooperfast_ssd' -DiskStorageFormat Thin -Location (Get-Cluster -Name 'yomama' | Get-Datacenter | Get-Folder -Name 'Discovered virtual machine') -ResourcePool 'yomama' -OSCustomizationSpec 'win2016x64'
This runs and the VM does deploy BUT! I get the error message below....
New-VM : 11/16/2018 9:13:57 AM New-VM The operation for the entity "win2016x64" failed with the following message:
"A specified parameter was not correct: hostname"
The cluster called "yomama" that it is deploying to has DRS on if that means anything...….lol
Any ideas? Remember, I'm still a noooob at this. (◔/‿\◔)
Hello,
I've written a script that migrates VM's from host to host serially as per the requirements of the person who needed it. After the migration is done the host is put in maintenance mode so it can be updated. I found that I needed to add an ability to move templates, as it doesn't seem to move them when the host is put into maintenance mode. As of the moment if the host doesn't have templates it will migrate all the VM's, but not move to putting the host in maintenance mode. If it has templates it will convert them and move them, but not set them back as templates. It will then put the host into maintenance mode though. Here's an excerpt from my script:
$cluster = Get-Datacenter -Name $dc[$answer - 1].Name | Get-Cluster | sort Name | Out-GridView -Title 'Select a cluster' -OutputMode Single #Gets the clusters in the datacenter
$mycluster = Get-Cluster $cluster.Name
$host1 = Get-Cluster "$mycluster" | Get-VMHost | where {$_.ConnectionState -eq "Connected"} | sort Name | Select Name,ConnectionState,PowerState | Out-GridView -Title 'Select the host to migrate VMs from' -OutputMode Single #Lists all hosts in Connected mode in the cluster
$fromhost = Get-VMHost $host1.Name
$host2 = Get-Cluster "$mycluster" | Get-VMHost | where {$_.ConnectionState -eq "Connected"} | sort Name | Select Name,ConnectionState,PowerState | Out-GridView -Title 'Select the host to migrate VMs to' -OutputMode Single #Lists all hosts in Connected mode in the cluster
$tohost = Get-VMHost $host2.Name
$selectedtemplates = Get-Template -Location $fromhost
$selectedvms = Get-VM -Location $fromhost #| sort Name | #Out-GridView -Title 'Select the VMs you wish to migrate' -OutputMode Multiple #Opens a window allowing you to click on the VM's you want to migrate
if($selectedvms){
foreach ($vm in $selectedvms)
{
Write-Host "Relocating VM:" $vm.Name "to" $tohost
Get-VM -Name $vm.Name | Move-VM -Destination $tohost -diskstorageformat thin #Moves to the new host one at a time
}
if($selectedtemplates.Count -gt 0) {
foreach ($template in $selectedtemplates)
{
Write-Host "Relocation Template:" $template.Name "to" $tohost
Set-Template -Template $template.Name -ToVM
Get-VM -Name $template.Name | Move-VM -Destination $tohost -diskstorageformat thin
Get-VM -$template.Name | Set-VM ToTemplate
}
Set-VMHost -VMHost $fromhost -State "Maintenance"
Sorry I don't know how to copy the code on here to make it look all pretty. Thoughts anybody?
I was looking to add an AD group to an ESXi host scripting it in. Don't want to use profiles as we would script all the post configs into the host and create the profile from there. The host will already be joined to the domain at that point in the script.
Get-VIAccount -Domain <Domain> -Group <Domain Group> ?
Thank you,
We had someone who has access to our environment make some changes to the permissions of some things. I am not very sure when it occurred as it didn't affect anyone for quite a while.
When I try to export "all users" events with the client, it fails. I am hoping that get-vievent will come to the rescue.
Is there any way to filter out most stuff and passing changes, for all users over say the last 30 days?
Hello everyone!
After recent discussion on vSphere Capacity planning, I thought I would share one of the tools I use for this purpose. This is a side project I've been working on for few months.
I present to you, my very own "VMware Capacity & Performance Report PowerCLI script (v2.1 Community edition)"
(Click here then click on "Download")
This is a complex PowerCLI script I wrote, that generates an e-mail report that gives you insight into the current state of your VMware vSphere environment's capacity. It generates tables, pie charts and line charts with information about CPU, Memory & Storage capacity, VM Provisioning Potential, Cluster Resilience and more. Check the script's #INFORMATION block for more information about prerequisites, script input and output.
Have a look at the report it generates and let me know what you think of it!
Please share your thoughts and comments!
Marc Davoli
http://ca.linkedin.com/in/marcvincentdavoli/
Edited on May 25 : Changed OneDrive link to updated script v2.1 with bugfix (for cluster names with a space in it)
Hi we are getting this same error when importing an OVA via PowerCLI 10.
PowerCLI: Import-vApp OVA: Hostname cannot be parsed. – ReadySetVirtual.com
The same work around to import an OVF worked using PowerCLI 10, however we need to import OVAs.
Is this a known issue with PowerCLI 10?
Hi Luc,
Good Morning
could you suggest how to pass array of clusters in orange line .below code works for one cluster.
its a similar approach as of previous code wherein getting output on console and then using read-host to set properties.
function get-clusterproperties_utilities
{
[cmdletbinding()]
param (
[parameter(mandatory = $true,
valuefrompipeline = $true,
valuefrompipelinebypropertyname = $true)]
[string[]]$clusters
)
foreach($clu in $clusters)
{
$cluster=get-cluster $clu
#$cluster.HAenabled
#$cluster.DrsEnabled
$output = New-Object -TypeName PSObject
$output|Add-Member -MemberType NoteProperty -Name 'clustername' -Value $cluster.Name
$output|Add-Member -MemberType NoteProperty -Name 'HA enabled' -Value $cluster.HAEnabled
$output|Add-Member -MemberType NoteProperty -Name ' DRS enabled ' -Value $cluster.DrsEnabled
$output|Add-Member -MemberType NoteProperty -Name ' DRS automationlevel ' -Value $cluster.DrsAutomationLevel
$output
}
$res=read-host "do yu wnt to enable cluster properties y/n"
if($res -eq 'y')
{
$clusternamee=read-host "speclify array of clusters"
foreach($c in $clusternamee)
{
$cluu=get-cluster $c
$cluu.name
#set-cluster -Cluster $cluu -HAEnabled:$true -DrsEnabled:$true -WhatIf
}
}
}
Getting error when runnig this code -- > Exception calling "AcknowledgeAlarm" with "2" argument(s): "The object has already been deleted or has not been completely created"
Connect-VIServer -Server $xxx -Credential $cred | Out-Null;
$alarmMgr = Get-View AlarmManager;
$rootFolder = Get-Folder -Name Datacenters;
$rootFolder.ExtensionData.TriggeredAlarmState.Acknowledged | Where {$_.Acknowledged -like "False"} | ForEach-Object -Process {$alarmMgr.AcknowledgeAlarm($_.Alarm,$_.Entity)};
$AllAlarms = $rootFolder.ExtensionData.TriggeredAlarmState | Select @{N='Alarm';E={(Get-View -Id $_.Alarm -Property Info.Name).Info.Name}},Time,OverallStatus,@{N='Entity';E={(Get-View -Id $_.Entity -Property Name).Name}};
Hi,
Can anyone please help me with script to get vcenter health status with following reports.
1. Datastores - <20%: details of datastore with free space less than 20%
2. Snapshot: details of existing datastores.
3. Disk consolidation : details of vms with required disk consolidation.
4.VM - Powered off :details of powered off vm's
5. Zombie Files : details of zombie files
6. VMWare Tools: details of vm's with vmtools not running or out of date or not installed.
7. Inconsistent folder name: Details of VM's with Inconsistent folder name.
We can get these details from rvtools, but i need powercli script or script to extract to these details from rvtools excel file.
Hi,
I want to get the size in GB, I am using the below scipt but I am unable to get in GB
Below show the size in KB
write-host ("The Volume Size on the FlashArray is : " + $purevol.Size)
Below format shows blank
write-host ("The Volume Size on the FlashArray is : " + $purevol.@{n='SizeInGB';e={[int]($_.Size/1GB)}})
Please help...
Hi,
I am unable to get the output from the below script
if ($lun -like 'naa.624a9370*|^c3776b2da*|^427be350a*')
{
$volserial = ($lun.ToUpper()).substring(12)
$pvol = $volumes | where-object { $_.serial -eq $volserial }
Write-Host "###########################################################################################################" -ForegroundColor Green
write-host ("The Volume is on FlashArray : " + $EndPoint.EndPoint)
write-host
write-host ("The Volume Name on the FlashArray is : " + $vol.name)
Write-Host "###########################################################################################################" -ForegroundColor Green
}
else
{
write-host
Write-Host "###########################################################################################################" -ForegroundColor Green
write-host 'This datastore is NOT a Storage Volume.'
Write-Host "###########################################################################################################" -ForegroundColor Green
}
If I replace below line
if ($lun -like 'naa.624a9370*|^c3776b2da*|^427be350a*')
with
if ($lun -like 'naa.624a9370*')
I am able to get the output but I want to add additional parameters to search other strings
Please help.
Hi all,
As I was creating vmk’s i found that I could enable vsan traffic, vmotion and management traffic but nothing there for vSphere replication and NFC, any ideas on how I might be able to do this with powercli?
I'm trying to write a script to perform the following:
Connect to Horizon Connection Server
Query all machines that are have a Machine Source = vCenter (linked clone) and display the following in a report (csv / html)
Name
Desktop Pool
Base Image
Last Compose
I'm not have much luck - any insight on a similar script that I can modify?
Horizon 7.0.4.
Thanks - Dan
Issue Details:
1. We use PowerCLI to get values from VMs. There are instances where the values fail to return. It is our belief that this worked flawlessly before and we can show that it still does in some instances. We developed a test script to reproduce the problem as well as show instances where things appear to work correctly. This script connects to a machine we chose. We provide administrative credentials and the script returns the value 12345. It does ten iterations of this task. We expect 10/10.
$creds = Get-Credential
$successes = 0; while ($true) {
$output = Invoke-VMScript -VM "MyVM" -ScriptText "return '12345'" -GuestCredential $creds
$output
if ($output.ScriptOutput) {$successes++}
if ($successes -eq 10) {break}
}
When we run this script against some servers it works flawlessly. That is the return is 10/10. When we look at the VM > Tasks & Events > Events we see the following successive events which are normal.
(1) Guest operation Create Temporary File performed.
(2) Guest operation Start program performed.
(3) Guest operation List processes Performed.
(4) Guest operation List processes Performed.
(5) Guest operation Initiate File Transfer from Guest Perform.
(6) Guest operations Delete File performed.
The system repeats these events for each successful iteration.
2. Our test script will make as many iterations as possible to get 10 successful results. Ideally, it would only have to make 10 attempts to get 10 results. But when there are failures, we have to make more than 10 attempts to get the desired results. I have seen it take as many as 19 attempts to get 10 successes.
3. As an additional data point, When running this script against the domain controller in an environment it works flawlessly. However, when running against a domain joined machine in the domain, the problem happens. If I watch the creation of the Powershell## file in the temp directory on the system. The ones that copy with 0 bytes are the ones that fail.
Any ideas?
Thanks!
Afternoon Communities .
I am having problems with querying TAGS and Storage Polices and it appears I am not the only one on communities .
VCSA6.02
PowerCLI 6.5.1 and 6.03 and .6.31.
When I run the following from PowerCli 6.5.1 :
Get-SpbmStoragePolicy -Namespace "Bronze Datastore Policy"
Or Just Get-SpbmStoragePolicy
I get Object reference not set to an instance of an object
I tried community solutions like setting date format to US English and accepting invalid certs .
https://www.rudimartinsen.com/2017/07/14/issues-with-get-spbm-powercli-cmdlets-and-vcenter-6-5/
No luck . Then I found
VMware PowerCLI Forum - VMware {code}
I did Get-Tag | Where {$_.Category -eq $null}
It returned quite a few uncategorized SRM-CG and SRM-PG ones .
I am however pretty sure I cannot delete or edit those , from names , they were clearly created by system : EG
Name Category Description
---- -------- -----------
SRM-CG-341213cf07293d273f81... Site Recovery Manager Consistency Group Tag for Replica...
SRM-PG-939d00673c75ea9c7a47... Site Recovery Manager Protection Group Tag for Protecte...
So I tried two other Windows Management server with PowerCLI 6.03 and 6.3.1 as some communities suggest its a but in PowerCLI 6.5.1
Now I cannot even do get-tag :
Index was outside the bounds of the array
Where to now ?
Any help would be greatly appreciated .
Ultimate goal is to get Storage Policies set to ensure Storage Tier and SRM protection are automatically dealt with during VM provisioning
Hi ,
I am looking for a script for below task in powercli
1- Script to add all ESXi Hosts in a vCenter to Domain for authentication (script should have an option to re-add a host to domain if it was already part of domain, but authentication is failing)
2- Retrieve last date of root password change from all ESXi hosts in a vCenter
3- Change the root password (with a randomly generated password meeting password complexity policy) of all ESXi hosts if the last password change date is more than 80 days and generate the output with the new passwords to update in password repository.
We have a script that dumps virtual machine portgroup information for a migration to a new vCenter server. When we are ready to cut everything open, we have the following:
$vms = get-content "c:\temp\$host.txt"
foreach ($vm in $vms) {
Invoke-Expression $vm
}
$vms=get-content"c:\temp\$host.txt"foreach ($vmin$vms) { Invoke-Expression$vm }
The $host.txt file contains a row for each virtual machine network adapter and is formatted like so:
Get-VM 'VMName' | Get-NetworkAdapter -Name 'Network adapter 1' | Set-NetworkAdapter -Portgroup PGName -confirm:$false
Right now the script is running them one at a time which causes VMs further down on the list to be offline for up to 30 seconds waiting for their turn. Could somebody please assist int he proper method to run them all at once or at the very least in a batch of 10?
Thanks!
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:
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 8) -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 8) -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
we dont have enterprise license to enable DRS in our cluster, however we are keep getting an error about imbalanced resource usage and manually we are balancing.
is there a way to do powercli to balance across the cluster?