Create a credentials file for vSphere

Instead of having to enter the username and passwords every time you are running a script it is a good idea to create a credentials file and encrypt it on your system.

Create encrypted file

# Create a PSCredential object
$Username = "<Your_vCenter_Username>"
$Password = Read-Host -AsSecureString "Enter your vCenter password"

$Credential = New-Object System.Management.Automation.PSCredential($Username, $Password)

# Save the encrypted credentials to a file
$Credential | Export-CliXml -Path "C:\vCenterCredentials.xml"

Write-Host "Credentials saved to C:\vCenterCredentials.xml"

This creates a file C:\vCenterCredentials.xml that contains your credentials in an encrypted format.

Script to Read Credentials and Connect to vCenter

# Load credentials from the encrypted file
$CredentialFilePath = "C:\vCenterCredentials.xml"

if (Test-Path $CredentialFilePath) {
    $Credential = Import-CliXml -Path $CredentialFilePath
    $Username = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().Password

    # Connect to vCenter using the credentials
    Connect-VIServer -Server "<vCenter_Server_Name>" -User $Username -Password $Password
    Write-Host "Connected to vCenter successfully."
} else {
    Write-Host "Credential file not found at $CredentialFilePath. Please create the file first."
}

Script Explanation:

Export-CliXml: Encrypts and saves the credentials securely to a file.
Import-CliXml: Reads the encrypted credentials back into a PSCredential object.
Test-Path: Ensures the credentials file exists before attempting to load it.
Connect-VIServer: Uses the loaded credentials to connect to the vCenter server.

Notes:

    The encryption is tied to the user account that created the file. Only the same user on the same machine can decrypt it.
    Replace <vCenter_Server_Name> with your actual vCenter server’s hostname or IP address.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Share on Social Media