Using Previously Connected vCenter Sessions with PowerCLI

When connecting to a vCenter Server over PowerCLI, I’ve leaned on a handful of methods to collect credentials for authentication. These are:

A String for the username and SecureString for the password

A System.Management.Automation.PSCredential type variable that contains a full set of credentials

The focus for both methods is to safely handle the password value, avoiding storing it in plain text (as a file or in memory). However, it dawned on me that in many cases there’s already an active session available on the user’s workstation, especially when the authentication took place through an iterative workflow that calls one or more cmdlets in series. Rather than connecting and disconnecting through each loop, I wondered if it wouldn’t be easier to simply connect and then re-establish the connected session.

Hello there, previously connected sessions!

PowerCLI uses a pair of global variables to store connection details.

$global:DefaultVIServer – The single default connection

$global:DefaultVIServers – A System.Array of default connections

The interesting tidbit is the SessionId key, which contains the session value needed to reconnect without supplying credentials. And so, to connect to a vCenter Server using the SessionId key, simply supply it to the Connect-VIServer cmdlet. Like so:

The flaw to this logic is that the Default server may not be the intended one. In some cases, the use of -AllLinked or multiple Default servers will make it more advantageous to search through the System.Array of sessions to find the correct one.

In that case, you may want to allow the user to input a value for a $vCenter variable and use the results to filter through the connection array. This may be a better method:

The takeaway here is that there’s lots of options when it comes to connecting to a vCenter Server, and not all of them require gathering a full set of credentials each time.

The Credential Store

Alternatively, it’s possible to toss credentials into an XML file. The Credential Store, or credstore, is used for this purpose. I’ll admit that I never really use this in production much – tinfoil hat and all – but it is an available option that works and is handy for development or test environments.

All three operate about as you’d expect. For a vCenter Server connection, you can use the -SaveCredentials parameter during the Connect-VIServer command. This will save your credentials into the Credential Store for that vCenter Server. Alternatively, use the New-VICredentialStoreItem cmdlet like so:

This also means that it’s simple enough to float the credentials file across your user profile, or to sync it using Dropbox and the like. Future connection requests to the host will use the saved username and password. Just be cautious … the use of Get-VICredentialStoreItem will return a plain text password!