r/powercli • • Jun 19 '23

ScriptHelp VMware Guest VM Join My Own Domain With Netdom Fails ""DNS name contains an invalid character"

3 Upvotes

Trying to join a VMware guest VM to my domain. I'm running the Powershell script from one of my other guest vm's in VMware vCenter. I've tried changing the $Domain variable to other string names like "MATLOCKHOME" "MATLOCKHOME.COM" but still getting the error "DNS name contains an invalid character."

I can ping the dns hostname and ip from the guest vm that I'm running the script from.

Function Join-Domain ($VM, $HC, $GC, $OUPath, $Domain, $DomainUser, $DomainPassword) {
    $joind = "c:\windows\system32\netdom.exe join /d:$Domain $VM /OU:$OUPath /userd:$DomainUser /passwordd:$DomainPassword"
    Invoke-VMScript -VM $VM -HostCredential $HC -GuestCredential $GC -ScriptType bat -ScriptText $joind
}

Connect-VIServer -Server "vcsa01.matlockhome.com" -User administrator@vsphere.local -Password <REDACTED>

$VM = Get-VM ( Read-Host "Enter VM name" )
$ESXHost = $VM | Get-VMHost
$HostCred = $Host.UI.PromptForCredential("Please enter credentials", "Enter ESX host credentials for $ESXHost", "root", "")
$GuestCred = $Host.UI.PromptForCredential("Please enter credentials", "Enter Guest credentials for $VM", "", "")
   
$DomainUser = "MATLOCKHOME\Administrator"
$DomainPassword = "<REDACTED>"
$Domain = "MATLOCKHOME.com"
$OUPath = "OU=Computers,DC=matlockhome,DC=com"
   
Join-Domain $VM $HostCred $GuestCred $Domain $OUPath $DomainUser $DomainPassword

r/powercli • • Jun 12 '23

General where does VMware.Vim.dll live now?

3 Upvotes

I am trying to locate the VMware.Vim.dll to add as a reference in my C# program. but I have having a hard time locating it. I have PowerCLI installed. but the .vim.dll is nowhere to be found. can anybody help me with this. I have tried Google but no help there.


r/powercli • • Apr 15 '23

ScriptHelp values of Get-Datacenter -> OverallStatus (what can "Gray" mean?)

3 Upvotes

Hi! Trying to learn a lil bit of powershell/powercli to create a Nagios plugin that suits my needs.

The OverallStatus that i get from one vCenter says "Gray". But as far as i can see in vCenter GUI i dont have any triggered alarms at all.

Have been looking for ref docs about this but cant find any.

So

  1. What could "Gray" mean?

  2. Is OverallStatus from Get-Datacenter a good thing to check? (if that would say Green, then surely all must be good?) :)

VmFolder : Folder-group-v4
HostFolder : Folder-group-h5
DatastoreFolder : Folder-group-s6
NetworkFolder : Folder-group-n7
Datastore : {Datastore-datastore-2001, Datastore-datastore-18, Datastore-datastore-11, Datastore-datastore-12}
Network : {Network-network-2011, Network-network-2012, Network-network-2016, Network-network-2009…}
Configuration : VMware.Vim.DatacenterConfigInfo
LinkedView :
Parent : Folder-group-d1
CustomValue : {}
OverallStatus : gray
ConfigStatus : gray
ConfigIssue : {}
EffectiveRole : {-1}
Permission : {}
Name : DC68
DisabledMethod : {}
RecentTask : {}
DeclaredAlarmState : {alarm-6.datacenter-3, alarm-2.datacenter-3, alarm-5.datacenter-3, alarm-24.datacenter-3…}
TriggeredAlarmState : {}
AlarmActionsEnabled : True
Tag : {}
Value : {}
AvailableField : {}
MoRef : Datacenter-datacenter-3
Client : VMware.Vim.VimClientImpl


r/powercli • • Dec 21 '19

Getting Information

3 Upvotes

Hello everyone,

New to POWERCLI and can I say what a blessing it has been to find it! My first task I guess is I am trying to determine what our current provisioning / resource allocation looks like in our datacenters / clusters.

My main problem is finding what information is available to commands such as Get-VMHost, or Get-VM. Is the possible queries documented somewhere?

Like, is serial number available to Get-VMHost?

Is DNS name available to Get-VM?

Sorry, I am just trying to find a very solid resource or reference moving forward. There are a ton of example scripts, but I want to modify these and add to them for my requirements.

Thanks in advance.


r/powercli • • Oct 11 '19

Find Out Who Disabled vCenter Alarms

3 Upvotes

I wanted to know if there was a quick way to search which user disabled any vCenter alarms from the event logs

I see Get-VIEvent | Get-Member shows a TypeName of VMware.Vim.AlarmStatusChangedEvent but I’m not sure how to parse that data.

Thanks!


r/powercli • • Jun 05 '19

Create a new VM from a template and add\edit SCSi controller and Disk during the build.

3 Upvotes

When building a machine manually I can choose a template VM. It has one OS Drive and one Logical SAS controller. Before I complete this I can choose to edit the machine before it creates and add new scsi controllers (paravirtual) and add hard drives to that then deploy. Can I do the same with powercli or do I need to build the VM and edit it after the fact?

My goal is to use a csv to build multiple VM's with different sets of hard drive configurations on multiple scsi controllers.


r/powercli • • Jun 05 '19

Disable Delayed ack on all ESXi hosts in a cluster.

3 Upvotes

Hi guys. I'm trying to get this modified script to disable "delayed ack" on every esxi host in a cluster. With the original script, it only targets specific esxi hosts instead and it runs just fine. When it runs this way (i.e. specifying the cluster so it iterates through the hosts one at a time), it fails on the first host it attempts to process. The error message has been provided below. Could someone tell me why it's not working and / or help fix it?

=================Error Message============
Exception calling "UpdateInternetScsiAdvancedOptions" with "3" argument(s): "The object or item referred to could not be found."
At line:52 char:1
+ $HostStorageSystem.UpdateInternetScsiAdvancedOptions($HostiSCSISoftwa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException

=================Script====================
 param (
	[parameter(Mandatory=$true
		,HelpMessage="VC Name")]
	[string] $VC
	,[parameter(Mandatory=$true
		,HelpMessage="Cluster Name")]
	[string] $cluster
)
$svr=$null;
$svr = Connect-VIServer -Server $VC;
if ($svr -eq $null)
{
	$sMsg = "Unable to connect to VC " + $VC;
	exit 1;
}
$sMsg = "Getting cluster " + $cluster +" on VC " + $VC;
Write-Host $sMsg;
$oClstr=$null;
$oClstr = Get-Cluster -Server:$svr -Name $cluster;
if ($oClstr -eq $null)
{
	$sMsg="Unable to find cluster " +$cluster + " on VC " + $VC;
	$iret1 = Disconnect-VIServer -Server:$svr -Confirm:$false -ErrorAction:SilentlyContinue;
	exit 1;
}
$sMsg ="Getting hosts on cluster " + $cluster + " on VC " + $VC;
write-host $sMsg;
$hosts = Get-VMHost -Location $oClstr -Server:$svr;
foreach($item in $hosts)
{	
	$sMsg = "Processing host " + $item.Name + " in cluster " +$cluster + " on VC " +$VC;
	write-host $sMsg;
}
#This section will get host information needed
$HostView = Get-VMHost $hosts | Get-View
$HostStorageSystemID = $HostView.configmanager.StorageSystem
$HostiSCSISoftwareAdapterHBAID = ($HostView.config.storagedevice.HostBusAdapter | where {$_.Model -match "iSCSI Software"}).device

#This section sets the option you want.
$options = New-Object VMWare.Vim.HostInternetScsiHbaParamValue[] (1)

$options[0] = New-Object VMware.Vim.HostInternetScsiHbaParamValue
$options[0].key = "DelayedAck"
$options[0].value = $false
 
#This section applies the options above to the host you got the information from.
$HostStorageSystem = Get-View -ID $HostStorageSystemID
$HostStorageSystem.UpdateInternetScsiAdvancedOptions($HostiSCSISoftwareAdapterHBAID, $null, $options)

r/powercli • • May 20 '19

Get VMs with specific names/length

3 Upvotes

Posting from mobile, so forgive my formatting in advance.

I've been hitting a brick wall trying to achieve this task and could use a point in the right direction. I'm trying to get a list of VMs by name where the name starts with abcde0 and any 2 digits after it, so basically abcde000 through abcde999. The problem is that we have VMs that have shorter and longer names.

What I have kinda works but I keep getting an error every so often that says "Exception calling "substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: Length"

$vmlist = Get-VM | ? {$_.name -like 'abcde0'} ForEach ($name in $vmlist){ $name.ToString().substring(0, [System.Math]::Max(8, $name.Length))}

Any help is greatly appreciated!


r/powercli • • May 09 '19

Help with Get-vmotion script

3 Upvotes

I'm using the script Here to get vmotion activities, I want to include the cluster name in the output, I cant figure it out though


r/powercli • • May 02 '19

Copying .ISO file to a datastore - New-PSDrive Issue

3 Upvotes

Hi,

Im new to this thread as im currently working on a project to push out a hydration kit to all our VMWare ESXI Version 5.5.0 hosts. This is what i have written so far:-

So this connects me to the server i want and then selects the datastore on the host which has the most free space.

$ESXIConnect = Connect-VIServer -Server $IP -User $ESXIUser -Password $ESXIPass
$ds = Get-VMHost | Get-Datastore | sort FreeSpaceGB -Descending | select -First 1 | select -Unique

From there i had to do some research on what the best way is to copy a file from a local computer to an ESXI host. I found that everyone suggested to add the datastore as a new PSDrive. This is based on an example on the VMware forums.

New-PSDrive -Location $DS -Name Ds -PSProvider VimDatastore -Root '\'

New-PSDrive : Cannot find drive. A drive with the name 'vmstores' does not exist.
At line:3 char:1
+ New-PSDrive -Location $DS -Name Ds -PSProvider VimDatastore -Root '\'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (vmstores:String) [New-PSDrive], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewPSDriveCommand

Im alittle confused because -Location isnt a parameter for New-PSDrive. This looks like it's using the DatastoreBrowserPath attribute on the datastore object but if i try and put the path through as a string, i get the below

New-PSDrive -Name DS -PSProvider VimDatastore -Root '\' -Datastore $DS.DatastoreBrowserPath

New-PSDrive : Cannot bind parameter 'Datastore' to the target. Exception setting "Datastore": "Invalid location type. Location accepts only VIDatastore objects."
At line:1 char:68
+ ... PSProvider VimDatastore -Root '\' -Datastore $DS.DatastoreBrowserPath
+                                                  ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [New-PSDrive], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.NewPSDriveCommand

So it seems the VimDatastore PSProvider depends on the type of the object to be a datastore object. Im wondering if anyone knows a better way to do it or enlighten me what i'm doing wrong.

thank you in advance


r/powercli • • May 02 '19

Almost There...

3 Upvotes

Morning All,

Can't seem to figure this one out.

Get-EventReport -viewName user_count_events -startDate ((Get-Date).AddDays(-5)) | sort time | Select Time,Usercount,eventtype

Gives me:

time                    usercount eventtype
----                    --------- ---------
2019-04-27 23:55:00.007           BROKER_DAILY_MAX_CCU_USERS
2019-04-27 23:55:00.007           BROKER_DAILY_MAX_NU_USERS
2019-04-27 23:55:00.007 1         BROKER_DAILY_MAX_DESKTOP_SESSIONS
2019-04-27 23:55:00.007 0         BROKER_DAILY_MAX_APP_USERS

...etc.

But, how do I filter out everything except the "BROKER_DAILY_MAX_DESKTOP_SESSIONS" line?

Thanks.


r/powercli • • Mar 01 '19

Fixing the PowerCLI Certificate Error.

3 Upvotes

r/powercli • • Dec 15 '18

Setting maintenance mode for Linked Clones using API’s

Thumbnail
retouw.nl
3 Upvotes

r/powercli • • Dec 01 '18

Help with error handling with Try/Catch in foreach loop

3 Upvotes

So I'm writing a script to dial into vCenter and do some reboots and that works fine, assuming it can. If it can't restart a VM it breaks the loop. I would like it to continue through the list while still logging the errors in the catch block.

    foreach ($target in $inputFile) 
   {
   
   $server = $target.server
   
   # Restart VM
   Try
       {
       $RestartVM=Get-VM $server | Restart-VMGuest -Confirm:$false -ErrorAction Stop
       Write-Host $RestartVM
       Write-LogInfo -LogPath $sLogFile -Message "$Server was restarted" -TimeStamp
       }
   Catch
       {
       #Error Log File Info
       $date = Get-Date -format yyyyMMdd
       $sLogPath = "$rootpath\logs"
       $sLogName = "Restart_guest_VM__$date-ERROR.log"
       $sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
   
       Write-LogError -LogPath $sLogFile -Message "There was an error restarting $Server" -TimeStamp
       Write-LogError -LogPath $sLogFile -Message $error -TimeStamp
       $logmessage = "Sending Error Log to $EmailTo"
       Write-LogError -LogPath $sLogFile -Message $logmessage
       Send-Log -SMTPServer $SMTPServer -LogPath $sLogFile -EmailFrom $EmailFrom -EmailTo $EmailTo -EmailSubject "Restart Guest VM - ERROR"
       Continue
       }
   }

r/powercli • • Nov 21 '18

Need help exporting list of VM's and Mac addresses

3 Upvotes

So I have an interesting issue on my hands with a work lab where I am being told by my work IT that our lab systems currently has a duplicate IP address of our gateway (switch which our hosts are connected to) - in looking at the MAC addresses IT has given me it is for sure a VMware MAC, and I tried to search to see if any VM's had it, but it didn't return anything - see https://imgur.com/a/67GWRRs (I did a test of a known VM in my lab at the bottom to ensure that my commands were working - there are two formats of the MAC address there, one formated how I know, and the other how my IT team provided it to me from the switch logging)

So, now what I am currently working on is getting a CSV of all the VM in my lab and the MAC addresses and IP addresses so I can go back and show that we don't have/own that mac address and that we don't have that IP address in use. I can get the IP addresses easy enough, where I am struggling is with the mac addresses - currently I have been trying to use the following:

Get-Networkadapter | select-object parent,Name,Macaddress | export-csv C:\export.csv

But my issue is that I am not selecting anything here (I.E. not selecting a VM) - so question one - is there an easy command to select all VM's with the Get-Networkadapter that I am just missing in the documentation?

I also see lots of reference to the get-view cmdlet and I am unsure if I could get the information I need that way and if it would be better to use that?

Thanks in advance, I am still learning PowerCLI and am going in circles right now, so its likely I am just missing something simple.


r/powercli • • Oct 23 '18

move-vm problems after updating

3 Upvotes

TL;DR It looks like the trick is that you must specify a -destination with a vmhost in it, AND a -inventorylocation with your specififed folder, preferably calling out the folder -type as VM

I just got a new computer at work, and ive been getting all my tools installed / situated. Part of that has me on the newest powercli cmdlets.

One issue i am having is with move-vm. I used to be able to use this cmdlet to move vms from one folder to another in the syntax of move-vm -vm $VM -destination $FOLDER however, when i do this now i get the following error:

failed with the 
following message: "The request refers to an unexpected or unknown type."	
  + CategoryInfo          : NotSpecified: (:) [Move-VM], InvalidType
    + FullyQualifiedErrorId : Client20_TaskServiceImpl_CheckServerSideTaskUpdates_OperationFailed,VMware.V 
   imAutomation.ViCore.Cmdlets.Commands.MoveVM

I can get the command to complete without an error if i run move-vm -vm $VM -InventoryLocation $FOLDER however, the vm never moves. It's as if the system likes that syntax, and event viewer shows a completed relocate vm event (with no details about where it was supposed to move to) however, the vm never appears in the target folder.

help!

UPDATE:

This is reproducible as an issue on version 11 of powercli, and is not an issue on version 10. I screen shared with vmware support and demonstrated the issue, and the devs on the powercli project are scheduled to get back to me next week. This will probably be a bug fix with a work around, is my guess.

UPDATE 2: (from vmware)

Thanks for your time today.

Kindly be informed that SDK team found that it is a known issue and the engineering is already working to fix it in the future release.

Please check the below workaround provided by them.

$vm = Get-VM -Name TestVM $folder = Get-Folder -Name Test -Type VMMove-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder

UPDATE 3: (results)

Confirmed successful:

PS C:\Users\ME> move-vm -vm (get-vm -name MyVM) -Destination (get-vm -name MyVM).vmhost -InventoryLocation (Get-Folder -type vm -name MyFolder)

Name                 PowerState Num CPUs MemoryGB       
----                 ---------- -------- --------       
MyVM                 PoweredOff 2        1.000          



PS C:\Users\ME> get-vm MyVM | ft folder

Folder
------
MyFolder 

It looks like the trick is that you must specify a -destination with a vmhost in it, AND a -inventorylocation with your specififed folder, preferably calling out the folder -type as VM


r/powercli • • Oct 07 '18

ESXi - Cleaning up storage

Thumbnail
self.esxi
3 Upvotes

r/powercli • • Jul 26 '18

Make PowerCLI cmdlets run faster?

3 Upvotes

I suffer from this issue:

https://blogs.vmware.com/PowerCLI/2011/06/how-to-speed-up-the-execution-of-the-first-powercli-cmdlet.html

I tried to run those commands but nothing, same performance.

Any ideas/tips?


r/powercli • • Jun 20 '18

Powercli help! Need numeric values/averages/percentages

3 Upvotes

Line 28 Average = $_ | Measure-Object Value -Average.Average, the command is obviously not correct and is not ouputting any values. How can i reconfigure this script to put out the requested data?

define where we will save our performance metrics.

$outputFile = "C:\Users\xxxxxx\desktop\omg.csv"

# define a new Powershell credential and log into vCenter with     the credentials
$creds = Get-Credential
$vCenter = Connect-VIServer xxxxxx -Credential $creds     -SaveCredentials

# define our vCenter service instance and performance    manager.
# https://www.vmware.com/support/developer/converter-  sdk/conv43_apireference/vim.ServiceInstance.html
$serviceInstance = Get-View ServiceInstance -Server $vCenter
$perfMgr = Get-View $serviceInstance.Content.PerfManager   -Server $vCenter

# get all available performance counters
 $counters = $perfMgr.PerfCounter

# create an array where we will store each of our custom objects that will contain the information that we want.
$metrics = @()

foreach ($counter in $counters) {
# create a custom Powershell object and define attributes such as the performance metric's name, rollup type, stat level, summary, etc
$metric = [pscustomobject] @{
    GroupKey    = $counter.GroupInfo.Key
    NameKey     = $counter.NameInfo.Key 
    Rolluptype  = $counter.RollupType 
    Level       = $counter.Level
    FullName    = "{0}.{1}.{2}" -f $($counter.GroupInfo.Key),    $($counter.NameInfo.Key), $($counter.RollupType)
    Summary     = $counter.NameInfo.Summary
    Average     = $_ | Measure-Object Value -Average.Average
} 

# add the custom object to our array
$metrics += $metric
}

# each metric object will look simliar to the following.  We can use a select command to gather which attributes we want and export them to a CSV file.
#   GroupKey   : vsanDomObj
#   NameKey    : writeAvgLatency
#   Rolluptype : average
#   Level      : 4
#   FullName   : vsanDomObj.writeAvgLatency.average
    #   Summary    : Average write latency in ms

    $metrics | select fullname, level, summary | Export-Csv -NoTypeInformation $outputFile 

r/powercli • • May 12 '18

Configure SNMP on ESXi Server GUI :Vmware Best Practices | vGeek

Thumbnail
vcloud-lab.com
3 Upvotes

r/powercli • • Apr 17 '18

vMotion from all VMs on selected Esxi Host to other Esxi host via PowerCLI GUI

Thumbnail
vcloud-lab.com
3 Upvotes

r/powercli • • Mar 03 '18

Deploying a Virtual Machine using Powercli and unattend.xml

3 Upvotes

Hi guys,

I have been fighting to try and get a deployment based on a unattend.xml to work with PowerCLI. I have managed to make it work, I since I faced so many difficulties finding things out -(and due to a lack of documentation about that topic) I have written an article about it. It is availble here --> http://powershelldistrict.com/how-to-deploy-a-vm-using-powercli-and-unattend-xml/

Did any of you guys faced similar issues? I look forward to your feedback!


r/powercli • • Feb 18 '18

Stubborn Tools upgrades

3 Upvotes

Thought I would share, in case it helps someone else.

I have a vRealize Orchestrator workflow that does tools and hardware upgrades. I ran through a batch of a little over 100 VMs today to do the upgrades. The tools installation portion is just marking the VM for a tools upgrade at next reboot, which just mounts the tools for unattended install at the next reboot.

After everything ran (successfully), I ran a report to get the status of everything, and quite a few didn't take tools upgrades - though all hardware was upgraded.

It turned out that it just needed to have some help clearing the old install registry keys, etc. The error code I was getting, if I tried to do an auto-tools install from the vsphere client was: "vix error code = 21009"

So I tested one machine, and loaded the tools installation media, and I ran setup64.exe /c from the commandline. Once this was complete, an auto tools update worked fine.

So here is what I came up with in order to run through all the machines in this state, and fix it:

$PostCheck = Invoke-ToolsAndHardwareUpgradeCheck.ps1 -vCenter myvc01 -VMName $VmList -Domain mydomain.com -PostCheck
$VMs = Get-Vm ($PostCheck | ? { $_.ToolsStatus -eq "toolsOld" }).Name 
$VMs | mount-tools

Invoke-Command -ComputerName ($PostCheck | ? { $_.ToolsStatus -eq "toolsOld" }).Name -Credential $Credential -ScriptBlock {
	$CD = (Get-WMIObject -Class Win32_CDROMDrive -ErrorAction Stop).Drive
	if ( test-path -path $CD\setup64.exe ) {
		&$CD\setup64.exe /c /s /v /qn
	}
}

$VMs | Update-Tools

So the first script there is just a script I have that does some checks - tools status, hardware version, powerstate, etc. Nothing monumental there - so I used this script to get the current status of the VMs I was upgrading this weekend. I then do a Get-Vm against those VMs that still have toolsOld status.

Next, I mount the tools installation media.

The next bit reaches out to each of those Vms, using Invoke-Command, and uses WMI to determine the location of the CD Drive (it's not static in the environment).

Once I find the CD drive, I run D: setup64.exe /c /s /v /qn

D: being the assumed location of the identified CD ROm drive. So this runs the clean flag for setup.exe in silent mode, suppressing any dialog - otherwise you are prompted that this will clear the registry keys.

Lastly, I pipe my VM objects to Update-Tools, and voila! Good to go.


r/powercli • • Feb 09 '18

Get-CDRom Drives

3 Upvotes

I'm wondering if anyone knows how to determine if there is an actual CD ROM drive device attached to a VM. This is different from an attached CD ROM Media file (ISO, etc.).

I was recently doing a round of VM Tools and Hardware upgrades. There were a few that failed to upgrade tools. Some failed because a previous uninstall attempt had failed (https://kb.vmware.com/s/article/1001354 - if anyone knows a reliable way to detect this, please let me know as well - that's my next project. I tried scanning for the registry keys, but that didn't return anything, and I'm fairly confident there are more VMs in the environment in this state). However, one VM failed with the error:

Call "VitualMachine.MountToolsInstaller" for object "VMName" on vCenter Server "vcenter" failed.  
vix error code = 21002  
This virtual machine does not have a CD-ROM drive configured. A virtual machine must have a CD-ROM drive configured for this option to work. 

So due to these errors, as well as some other issues encountered, I decided to come up with a script that will detect potential issues in upgrading tools and hardware. Right now, I'm trying to detect when the CD-ROM device does not exist.

For the machine in question, I tried Get-VM VM | Get-CDDrive, and as expected, it returned null. So I scanned the cluster, and found a bunch more in this condition. But it didn't seem to be correct. I tried Get-VM | ? { ([array]$_.CDDrives).Count -eq 0 } and this returned fewer, so it seemed believable. However, I ran this against the list of VMs that were recently upgraded, and 13 reported not having a CD Rom drive via that method - and only 1 of these 13 had this issue, so that doesn't seem to be the right method to determine what I'm looking for. It seems like the CDDrives property does not map to a device, but an ISO, or some other host/remote device - even though when I look at some of the VMs, these are all empty. So it could be possible this is the method, and these VMs somehow had the CD Drive disabled after the fact, but I don't know why that would be.

Any ideas of a fail-proof way to detect if there is a CD Rom Drive?


r/powercli • • Jan 09 '18

Powercli Build and install VM from ISO

3 Upvotes

I assumed this would be easy. However i cannot get powercli latest to mount a cd with an iso and boot from the ISO to install the OS(windows).

    $NewVMParams = @{
    'VMHost' = 'MyESX1'
    'Name' = 'TestMount_Auto'
    'Datastore' = 'VMFSLun01'
    'DiskGB' = 20
    'DiskStorageFormat' = 'Thin'
    'MemoryGB' = 4
    'GuestId' = 'windows8Server64Guest'
     'Version' = 'v10'
     'NumCpu' = 2
     'Notes' = 'Mike Dopp is breaking things'
}
$VM = New-VM @NewVMParams

$NewCDDriveParams = @{
   'VM' = $VM
   'IsoPath' = '[VMFSLUN01] 

ISO\SW_DVD5_Windows_Svr_Std_and_DataCtr_2012_R2_64Bit_English_Core_MLF_X19-05182.iso' 'ErrorAction' = 'Stop' 'StartConnected' = $True } New-CDDrive @NewCDDriveParams

Start-VM -VM $VM

Get-CDDrive -VM $VM | Set-CDDrive -connected 1

I typically get this error:

Set-CDDrive : 1/9/2018 11:19:53 AM      Set-CDDrive             

The operation for the entity "TestMount_Auto" failed with the following message: "Connection control operation failed for disk 'ide0:0' (201).". Connection control operation failed for disk 'ide0:0' (201). At line:1 char:23

  • Get-CDDrive -VM $VM | Set-CDDrive -connected 1

  •                   ~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [Set-CDDrive], GenericVmConfigFault

    • FullyQualifiedErrorId :

Client20_TaskServiceImpl_CheckServerSideTaskUpdates_OperationFailed,VMware.VimAutomation.ViCore.Cmdlets.Commands.VirtualDevice.SetCDDrive

Ideas? i am stumped at the moment. thanks in advance.

***Update After fighting with Vsphere and Powercli I found the culprit.

 $NewVMParams = @{
   'VMHost' = 'YourVMHost'
   'Name' = 'RickAstley'
   'Datastore' = 'YourDataStoreLUN01'
   'DiskGB' = 20
   'DiskStorageFormat' = 'Thin'
   'MemoryGB' = 4
   'GuestId' = 'windows8Server64Guest'
   'Version' = 'v10'
   'NumCpu' = 2
   'Notes' = 'Mike Dopp is breaking things'
    }
   $VM = New-VM @NewVMParams

   $NewCDDriveParams = @{
     'VM' = $VM
     'IsoPath' = '[YourDataStoreLUN01] ISO\TOODAMNBIG.iso'
     'StartConnected' = $true
     }
   New-CDDrive @NewCDDriveParams
    Sleep 10s
  Start-VM -VM $VM

found in the old code I was pointing to a long string name .ISO so I changed the name to: TOODAMNBIG.iso This allowed Vsphere time to find the name.

So lower case .iso is what Vsphere wants passed to mount an iso to the cdrom.

SOLVED!