Home > Blogs > VMware PowerCLI Blog > Tag Archives: VMware

Tag Archives: VMware

VSAN and vSphere Flash Read Cache cmdlets

Today a new VMware fling has been released, and it’s fantastic!  By now I am sure you have probably heard all the buzz from VMworld and with the 5.5 release and announced betas.  Two of the most talked about technologies are vSphere Flash Read Cache (vFRC) released in the new vSphere 5.5 version and also VSAN which was announced as a beta.

Today a new VMware fling was added to the site called “PowerCLI Extensionshere which allows you to use both VSAN and vFRC from PowerCLI, this gives you the added cmdlets needed in your PowerCLI session to automate two of the latest and greatest features from VMware.

Continue reading

Opening the Virtual Machine Remote Console through PowerCLI

With the 5.5 R1 release PowerCLI got even better. With the introduction of the new Open-VMConsoleWindow cmdlet you can access the virtual machine console of both vCenter Server and vCloud Director virtual machines. To open a virtual machine console window, simply pass a powered-on virtual machine to the Open-VMConsoleWindow cmdlet:

Get-VM “Win2k3” | Open-VMConsoleWindow

As a result, the cmdlet opens a Web page containing the virtual machine remote console: Continue reading

Joining ESXi hosts to a domain and granting permissions with PowerCLI

Recently I was asked by an administrator to help him automate the process of joining ESXi Hosts or as PowerCLI refers to them “VMhosts” to a domain and granting permissions for a domain user with PowerCLI.

In this post I am going to show you how this can be done with a few lines of code and also share my lessons learned throughout this process. Let’s assume that you have list of VMhost IP addresses and all VMhosts have the same local administrator credentials, you want to join them to a domain and grant permissions for a domain user or group account assigning it a specific role. In the script I assume the role exists on the VMHost but later I will show you how to create a custom role.

The Set-VMHostAuthentication cmdlet is used for joining a VMhost to a domain. You should have in mind that the full domain name must be specified on the Domain parameter of the cmdlet.

Get-VMHostAuthentication -VMHost <VMHost>| Set-VMHostAuthentication -Domain <domain fullname> -User <domain user name for authentication> -Password <password for authentication> -JoinDomain -Confirm:$false

The New-VIPermssion cmdlet is used for creating permissions for a specified user. The user is obtained with the Get-VIAccount cmdlet which has the ability to retrieve Domain user or group accounts when the VMHost is joined to a domain. In contrast to Set-VMHostAuthentication the Domain parameter of Get-VIAccount expects the domain alias instead of domain full name.

You should also be aware that if you don’t specify an Id filter to the Get-VIAccount cmdlet it returns the maximum 5000 results and for domains with many accounts this could be a constraint. So it is recommended to use Id filter of the cmdlet itself instead of applying filtering over its results.

To obtain domain user accounts use –User switch.

Get-VIAccount -Domain <domain alias> -User -Id <user name filter>

To obtain domain group accounts use –Group switch.

Get-VIAccount -Domain <domain alias> -Group -Id <group name filter>

To grant permissions you should specify account to Principal parameter returned by the Get-VIAccount cmdlet, role which can be obtained by Get-VIRole or specified by name and entity which in our case will be the VM host.

New-VIPermission -Principal <VIAccount> -Role <VIRole> -Entity <VMHost>

Here is the entire script with a lot of input parameters needed by the used cmdlets in the script but the script itself is not complex:

param (

   [Parameter(Mandatory=$true, HelpMessage=“List of VM host IPs”)]

   [ValidateNotNull()]

   [string[]]

   $vmHostIPs,

 

   [Parameter(Mandatory=$true, HelpMessage=“VM Host User Name”)]

   [ValidateNotNull()]

   [string]

   $vmHostUserName,

 

   [Parameter(Mandatory=$true, HelpMessage=“VM Host Password”)]

   [ValidateNotNull()]

   [string]

   $vmHostPassword,

 

   [Parameter(Mandatory=$true,HelpMessage=“Domain full name, required for joining hosts.”)]

   [ValidateNotNull()]

   [string]

   $domainlFullName,

  

   [Parameter(Mandatory=$true,HelpMessage=“Domain alias, required for retrieving domain accounts.”)]

   [ValidateNotNull()]

   [string]

   $domainAlias,

 

   [Parameter(Mandatory=$true, HelpMessage=“User name for domain authentication”)]

   [ValidateNotNull()]

   [string]

   $domainUser,

 

   [Parameter(Mandatory=$true, HelpMessage=“Password for domain authentication”)]

   [ValidateNotNull()]

   [string]

   $domainPassword,

  

   [Parameter(Mandatory=$true, HelpMessage=“Domain user name for which permissions will be granted”)]

   [ValidateNotNull()]

   [string]

   $userNameToGrantPermissions,

  

   [Parameter(Mandatory=$true, HelpMessage=“The name of the role you will assign to the user”)]

   [ValidateNotNull()]

   [string]

   $roleName

)

 

 

foreach ($vmHostIPin$vmHostIPs) {

    # Establish connection to a VMHost

    $vmHostConnection= Connect-VIServer-Server $vmHostIP -User $vmHostUserName -Password $vmHostPassword

      try {

            # Get VMHost instance

            $vmHost= Get-VMHost -Server $vmHostConnection

     

            # Join the VMHost to a domain

            Get-VMHostAuthentication -VMHost $vmHost | Set-VMHostAuthentication -Domain $domainlFullName -User $domainUser -Password $domainPassword -JoinDomain -Confirm:$false

 

            # Get a domain account

            $viAccount= Get-VIAccount -Domain $domainAlias -User -Id $userNameToGrantPermissions        

            if (-not $viAccount) {

                  throw “VIAccount with Id ‘$userNameToGrantPermissions’ not found in domain ‘$domainAlias'”

            }

 

            # Get role to assign

            $viRole= Get-VIRole -Name $roleName

            if (-not $viRole) {

                  throw “VIRole with name ‘ $viRole’ not found.”

            }

 

            # Add permissions on VMHost

            New-VIPermission -Principal $viAccount -Role $viRole -Entity $vmHost         

      } catch {

            Write-Error (“The following error has occurred for VMHost ‘$vmHost’: rn”+$_)

      } finally {

            Disconnect-VIServer $vmHostConnection -Confirm:$false

      }

}

 

As you can see the script opens a connection to each VMhost, joins it to the domain and creates permissions for a specific domain account. It relies on the existing role on the VMHost, but it can be easily modified to create a custom role and assign it to the obtained user.

To create a new custom role the New-VIRole cmdlet needs to be used specifying a name and list of privileges on its input. Here is an example:

New-VIRole -Name MyCustomRole -Privilege ‘Anonymous’, ‘View’, ‘Read’, ‘Power On’, ‘Power Off’

The script is calling the Get-VIAccount with a –User switch parameter which filters on domain user accounts. In order to retrieve a domain group account the –Group switch parameter should be used.

So the script looks pretty simple and straightforward but running it I’ve experienced the following problem. Sometimes Get-VIAccount failed to retrieve the domain user immediately after joining the VMhost to the domain and I received the following error “Error accessing directory: Can’t bind to LDAP server for domain: <DOMAIN>”.

It seems that synchronization with active directory needs some time after a host is joined to the domain and the problem is not 100% reproducible. So I solved it with a simple retry-wait mechanism on retrieving domain users.

# Get a domain account

$viAccount=$null

$retryCount= 5

while ((-not$viAccount) -and ($retryCount-ge 0)) {

      try {

            $viAccount= Get-VIAccount-Domain$domainAlias-User-Id$userNameToGrantPermissions

      } catch {

            Write-Error “Getting VIAccount with Id ‘$userNameToGrantPermissions’ failed with the following error: rn $_”

            Write-Host “Next attempt in 5 seconds”

            Start-Sleep -Seconds 5

}

$retryCount

}

Conclusion

In conclusion here are the lessons learned from this task:

  1. Get-VIAccount requires to specify the domain alias to Domain parameter
  2. Get-VIAccount limits the results to 5000
  3. Sometimes Get-VIAccount fails to obtain domain users immediately after a VMhost is joined to a domain.

imageThis post was created by Dimitar Milov…

Dimitar joined VMware and PowerCLI team in the beginning of 2011. He is member of the quality engineering part of the team and his main role is the functional verification of the vSphere, vCloud and License PowerCLI components.

As all members of the team he is working to deliver a good and valuable product. He is also working to improve all processes and tools involved in product development and validation.

VDS Export/Import with PowerCLI

One of the great new features introduced in vSphere 5.1 was the ability to export and import the configuration of your vSphere Distributed Switch (VDS) and port groups to a file.

This gives you a quick restore method in case of issues or misconfigurations and also allows you to copy the entire VDS or port group configuration to a new VDS.  This feature is detailed by this VMware KB and is available via the vSphere Web Client, below you can see how we would do this via the web client:

image

Exporting the configuration with PowerCLI

With the introduction of the VDS cmdlets in PowerCLI 5.1 R2 we can also automate this process using the Export-VDSwitch and

Continue reading

PowerCLI Lab Online – Sign up now for the public beta

If you were at VMworld in 2012 you may have attended the Hands on Labs (HOL), this is normally one of the most popular areas at VMworld as it’s a time when people can use the applications they don’t currently have installed in their own environments, they can use a virtual environment to follow instructions and see how the applications really work.

One of the most popular labs at VMworld is always the PowerCLI Lab, this was no exception in 2012, every year the PowerCLI team does a great job of adding new features to the latest version of PowerCLI and this is always a great way to check those features out in a test environment.

There has always been one issue with the HOL though, once you leave VMware you say goodbye to the HOL as access was previously at the event only….. Until Now.

There is now a public beta of the HOL Online, this gives you access to a number of different HOL Online for you to take at your own leisure and sat at the comfort of your own desk.

How do I sign up?

To sign up simply go to http://hol.vmware.com and click on the link as highlighted below:

image

Once you have filled out a few questions you will need to wait for your account to be activated (I have been assured this will be fairly quick).  Once activated you will be able to click on the “VMware Hands-on Labs Online” link as above and access a number of different labs, complete with their own isolated environment and full step by step documentation to run through the lab chosen.

How do I find the PowerCLI Lab?

Once you have gained access to the HOL and signed in use the left hand menu to select “Cloud Infrastructure”

image

Now scroll down the list on the right until you see the PowerCLI Lab, then click Enroll.

image

Once you have done this the selected Lab will be added to “My Enrollments” where you will be able to click the “Start this LAB” button to launch the lab as below:

image

The LAB will now start and you will have access as seen below:

image

Retrieving vCloud Director VM Hard Disk size

I was asked recently if we were able to retrieve the disk space of a VM in vCloud Director through PowerCLI, on checking this I found that it is not currently part of the CIVM object and also there is currently no Get-HardDisk cmdlet equivalent like in the vSphere snapin.

After looking through the REST API Reference Documentation –> User Operations I found an entry for the VM VirtualHardwareSection  and specifically the disks which can be found as can be seen here: GET /vApp/{id}/virtualHardwareSection/disks

The virtualhardwaresection is easily accessed via PowerCLI using the extensiondata property which allows access to the back end API, I could then find my disk properties by filtering on the description of Hard Disk as in the example below:

(Get-VM MyCloudVM).ExtensionData.getvirtualhardwaresection().Item | Where { $_.Description -like “Hard Disk”}

Now I had the hard disk I noticed that part of the information was the capacity as highlighted below:image

With this information I could then find the capacity of the disk and add the information I needed into more of a friendly PowerShell property to the Hard Disk object.

So tying this all back together we could easily use the .ExtensionData reference to create our own Advanced PowerShell function to return the hard disk information for any CIVM.

Example

The following shows an example of how to use this new function and the output, this of course can also be used to export into CSV/HTML/Text or any other format PowerShell can be used with, it is also great for reporting on where the disk space in your cloud is being used!

image

The Code

Function Get-CIVMHardDisk {
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$CIVM
)
Process {
$AllHDD = $CIVM.ExtensionData.getvirtualhardwaresection().Item | Where { $_.Description -like “Hard Disk”}
$HDInfo = @()
Foreach ($HD in $AllHDD) {
$HD | Add-Member -MemberType NoteProperty -Name “Capacity” -Value $HD.HostResource[0].AnyAttr[0].”#text”
$HD | Add-Member -MemberType NoteProperty -Name “VMName” -Value $CIVM.Name
$HDInfo += $HD
}
$HDInfo
}

}

Back to Basics: Connecting to vCenter or a vSphere Host

Following my previous post which took you through the install of PowerCLI I thought it was time to add another back to basics (B2B) post and show how to take the first step in using PowerCLI… Connecting to your vCenter or vSphere host.

Yes, PowerCLI can be used to connect to both vCenter and also the vSphere host independently, of course not all the cmdlets will be relevant if you connect to just the host but still, this can be useful during the initial setup or automated deployments of the complete infrastructure.

How to connect

If you are connecting to either a vCenter server or a vSphere Host the cmdlet is the same, you can use the Connect-VIServer cmdlet to connect to both of these (even at the same time), lets take a look at an example:

C:\PS>Connect-VIServer -Server vcenter01 -User admin -Password pass

In the above example you can see we are connecting to our vCenter server called “vcenter01” with a username and password to gain access to the vCenter server, we did not specify a protocol or port, by default HTTPS and port 443 is assumed which is the same as the vSphere Client or Web Client, unless you specify a –port or –protocol parameter for the cmdlet.

Credentials

In the example above we used the –User and –Password parameters to pass through the credentials but this might not always be what you want to do, especially as PowerShell files are plain text!  There are multiple ways in which we can specify the credentials or store the credentials, its really up to you which you use and which is best suited for your situation.

Continue reading

PowerCLI 5.1 Release 2 Now Available

PowerCLI 5.1 Release 2 has now been released and can be downloaded here.  As always you will find some great new features, bug fixes and enhancements which make PowerCLI even better than before… I know its hard to believe but its true.

VDS Cmdlets

PowerCLI SnapinsWhenever I would ask the question at VMUG’s or VMWorld, “What would you like to see next from PowerCLI” I would always get the same answer “Support for Virtual Distributed Switches!”.

Previously there has been a fling available and also some work created by community member “Luc Dekens” to use VDS, this was a great start but in some cases was not a sustainable solution as it was either not supported or more complicated to maintain or use.

I am now pleased to tell you that PowerCLI has a new snapin, this snapin is called VMware.VimAutomation.VDS and is for managing Virtual Distributed Switches.

Introduced are 14 new cmdlets which will allow you to perform actions against your VDS configuration, we can use the Get-VdsCommand cmdlet to list the new cmdlets.

An overview of these are below:

Cmdlet Name Cmdlet description
Add-VDSwitchPhysicalNetworkAdapter This cmdlet adds host physical network adapters to a distributed switch.
Add-VDSwitchVMHost This cmdlet adds hosts to the specified distributed switch.
Export-VDPortGroup This cmdlet exports the configuration of a specified distributed port group to a specified .zip file.
Export-VDSwitch This cmdlet exports the configuration of a specified vSphere distributed switch to a .zip file.
Get-VDPortgroup This cmdlet retrieves distributed port groups.
Get-VDSwitch This cmdlet retrieves vSphere distributed switches.
New-VDPortgroup This cmdlet creates distributed port groups.
New-VDSwitch This cmdlet creates vSphere distributed switches.
Remove-VDPortGroup This cmdlet removes distributed port groups.
Remove-VDSwitch This cmdlet removes vSphere distributed switches.
Remove-VDSwitchPhysicalNetworkAdapter This cmdlet removes host physical network adapters from the distributed switches they are connected to.
Remove-VDSwitchVMHost This cmdlet removes hosts from the specified distributed switches.
Set-VDPortgroup This cmdlet modifies the configuration of distributed port groups.
Set-VDSwitch This cmdlet modifies the configuration of vSphere distributed switches.

Remember each of these cmdlets has help built in, to access the help including examples of how you might use these cmdlets use the following:

Get-Help cmdletname –full

PowerShell v3 Support

As well as the new cmdlets for working with Distributed switches and all the other great enhancements in PowerCLI 5.1 Release 2 we made sure we listened to our customers and with the release of PowerShell version 3 it seams that a lot of people are already making use or planning to install PowerShell v3.

You will be happy to know that PowerCLI now supports PowerShell v3, this not only gives you support from VMware but also we are now able to take advantage of some of the great enhancements which PowerShell v3 brings.

Some PowerShell v3 examples…

Simplified Syntax… Making PowerShell and therefore PowerCLI easier to read and quicker to type we can use simplified syntax to give us even more English like statements, before we would have needed to use the {} brackets to compare a property, now we are able to type it the same way we would think it…

SNAGHTML26e15701_thumb3

The above simple example shows all virtual machines which are powered on.

vCloud Director 5.1 Support

With PowerCLI 5.1 R2 we have also added support for vCloud Director 5.1, you can now automate the latest version of vCloud director using both PowerCLI and PowerCLI for tenants in a vCloud Director 5.1 environment.

image_thumb2

PowerCLI 5.1 and the future

Recently I have had some questions from people using PowerCLI, these are mainly related to confusion around the 5.1 release of VMware products and the way that PowerCLI works so I wanted to use this blog post to answer some of these questions but also to confirm that the future for PowerCLI is bright.

Q.  “Does PowerCLI work with the vCenter Server Appliance?”image

A. Yes it does, PowerCLI uses the vCenter APIs, in fact the best place to install PowerCLI is the same place that you would use the vSphere Client from, this is normally the vSphere admins workstation or a windows machine used solely for scheduled tasks.  PowerCLI connects to the vCenter APIs and therefore both Windows and the appliance versions of vCenter work with PowerCLI 5.1.

Q. “Does PowerCLI work with the vSphere Web Client?”

A.  A common question and yet in reality you do not need the C# vSphere Client or the vSphere Web Client in order for PowerCLI to work, everything you need is inside the installer for PowerCLI, just install it (instructions here) and your set.

Q. “With VMware releasing more and more Linux related appliances what does this mean for PowerCLI?”

A. PowerCLI is one of VMware’s most successful and well loved automation and troubleshooting tools by vSphere and vCloud Director Admins, as I said in the answer to a previous question, it connects directly to the vSphere APIs, it doesn’t care what is hosting them.

Whilst I can not discuss the roadmap for PowerCLI I can certainly say its as strong as ever and we will continue to wow the users of PowerCLI with the latest features and updates.

Q. “Does Onyx work with vSphere 5.1?”image

A. For those of you who are not aware of what Onyx is, it’s a VMware Fling which sits in-between your vCenter and your vCenter Client, it intercepts the traffic and translates it into PowerShell code, not nicely formatted PowerCLI type cmdlets but still a great place to look if you need to find a way to do something quickly.

You hit play on the Onyx client and the fun begins, anything you do in the vSphere client from then on is captured and represented as code, and not just PowerShell code but also C#, vCO JavaScript and  Raw SOAP messages.

So does it work with 5.1 ?  Yes of course it does, but only when using the C# client, obviously the vSphere Web Client works differently and therefore Onyx is unable to capture the actions you take in the web client and turn them into code, as this is a fling I can not make any promises of if or when this will be updated to work with the web client but obviously the challenges are different.  In the meantime make sure you use the C# client when you want to capture the code.


Hopefully this will help eliminate any questions about PowerCLI and how it works with 5.1 and the future, if you have any further questions please add a comment to this post and we will do our best to answer them.

PowerCLI 5.1 Poster

Following the release of PowerCLI 5.1 there is of course a new PowerCLI Poster, those of you who attended VMworld San Francisco may have been lucky enough to grab one of the few posters we had there, they went very quick and I’m sorry to the people who did not get one.

We plan on having some at VMworld Barcelona (No guarantees) so make sure you attend some of the PowerCLI sessions to get your copy.

In the meantime, for those of you who could not wait and want to print your own copy right now please find below the latest PowerCLI 5.1 poster including a list of all the new cmdlets and the cmdlets in the new PowerCLI for vCloud Tenants snapin.

Download the poster here, this is ideal for printing on large printers or even just keeping on the iPad or as a PDF for reference.

PowerCLI Poster