For our first cmdlet on PowerShell Friday we are going to connect to vCenter.

Before we can do anything useful on an ESXi host or vCenter we need to connect to the server. Connecting to vCenter or an ESXi host is done with the command:

If you enter this at the PowerCLI prompt you will be prompted for the values, like this:


If you didn’t change the certificates for your hosts or vCenter server you will get a warning about the certificate ‘WARNING: There were one or more problems with the server certificate’ and so on. If you didn’t change the certificate this is normal message. More important is the message:  “WARNING: THE DEFAULT BEHAVIOR UPON INVALID SERVER CERTIFICATE WILL CHANGE IN A FUTURE RELEASE”, which speaks for itself.

Connect-VIServer will prompt you for a username and password, after which you get an object that contains the connection to vCenter.

PowerCLI-Login PowerCLI-Login2

Now when you run a command it will run with the connection you set up, for example Get-VM  to list all VMs in your vCenter.

If you don’t like to popups and want to do it all from a script you can do the following:

When you want to use this in your scripts it is not very safe of course. Your password is visible in plain text, and it will be visible in your history if you run it like this from the command line. If you want to use usernames and passwords in text files it is better to use the standard PowerShell stuff for this, the PSCredential object. You can construct a PSCredential object with:

Again, if you don’t want the prompt you can generate it completely on the command line:

You will get prompted for a password. Now if you want to connect to vCenter you can use:

If you want to connect to more vCenter servers at the same time, or just don’t like generic connecting there is good news. You can assign the connection object to a variable. With that variable you can do other stuff as shown in the next example:


Secure Strings

Now, I know I said this post was on connecting to vCenter, but I think it is very important to be secure from the start, so the whole “password in a script” is not something you should be doing. But sometimes you can’t get around on using accounts with passwords in your scripts. In that case it is better to use the following:

If you want to use that password later on you can read the file containing the encrypted password again: