Last active
March 31, 2024 18:55
-
-
Save AfroThundr3007730/f7d4877e1e2a20e7efe38f9965b6c3b5 to your computer and use it in GitHub Desktop.
Automate PowerCLI connection to vCenter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
Updated version available in my HelperFunctions module.