# encoding: ascii
# api: powershell
# title: testesr
# description: This code allows for the secure storing of an active directory password and then using it for connecting to exchange or active directory. This snippet will prompt the administrator for a username only, collect the password from the securely stored file, and then assemble a powershell credential object for use.
# version: 0.1
# author: Lubinski
# license: CC0
# x-poshcode-id: 6611
# x-derived-from-id: 6612
# x-archived: 2016-11-09T11:56:41
# x-published: 2016-11-06T21:15:00
#
#
#STORED CREDENTIAL CODE
$AdminName = Read-Host "Enter your Admin AD username"
$CredsFile = "C:\$AdminName-PowershellCreds.txt"
$FileExists = Test-Path $CredsFile
if ($FileExists -eq $false) {
Write-Host 'Credential file not found. Enter your password:' -ForegroundColor Red
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $CredsFile
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\$AdminName,$password}
else
{Write-Host 'Using your stored credential file' -ForegroundColor Green
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\$AdminName,$password}
sleep 2
Write-Host 'Connecting to Active Directory'
#Establishes connection to Active Directory and Exchange with the specified user acccount and password.
Connect-QADService -Service 'gbay-ad01' -Credential $Cred -ErrorAction Stop | out-Null
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://server.fqdn.com/PowerShell/ -Credential $Cred -Authentication Kerberos -ErrorAction SilentlyContinue
Import-PSSession $Session -ErrorAction SilentlyContinue -AllowClobber
if(!$?)
{write-host "Failed importing the exchange pssession, exiting!"
exit}
#END OF STORED CREDENTIAL CODE