Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active March 31, 2024 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/f7d4877e1e2a20e7efe38f9965b6c3b5 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/f7d4877e1e2a20e7efe38f9965b6c3b5 to your computer and use it in GitHub Desktop.
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
}
}
@AfroThundr3007730
Copy link
Author

Updated version available in my HelperFunctions module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment