Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automate PowerCLI connection to vCenter
# Automated PowerCLI connections to vCenter Server
# Script will use stored PSCredentials if user is unprivileged
function AutoConnect-VIServer () {
Param(
[string]$server = 'vcenter'
)
# Check if user is in a group with vCenter permissions
if ([System.Security.Principal.WindowsIdentity]::GetCurrent().Groups.Translate(
[System.Security.Principal.NTAccount]) -contains 'DOMAIN\vCenter_Admins') {
# Connect to vCenter using existing user token
[void](Connect-VIServer (Resolve-DnsName $server).Name)
}
else {
# PSCredentials are unique per (user,machine) pair, so the filename changes too
$filePath = $env:APPDATA + '\' + ((
[System.Security.Cryptography.HashAlgorithm]::Create('SHA1').ComputeHash(
[System.Text.Encoding]::UTF8.GetBytes("$env:USERNAME,$env:COMPUTERNAME")
) | ForEach-Object { $_.tostring('x2') }
).toupper() -join '')
if (!(Test-Path $filePath)) {
# Save PSCredential to file if it doesn't exist
$cred = Get-Credential -Message 'Enter credentials for VMWare Admin:'
$cred.UserName, ($cred.Password | ConvertFrom-SecureString) -join ',' |
Out-File $filePath
}
if (!$cred) {
# Load PSCredential from file
$user, $pass = (Get-Content $filePath).Split(',')
$cred = [System.Management.Automation.PSCredential]::new(
$user, (ConvertTo-SecureString $pass)
)
}
# Connect to vCenter using stored PSCredential
[void](Connect-VIServer (Resolve-DnsName $server).Name -Credential $cred)
$filePath, $user, $pass, $cred = $null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment