47 lines
2.5 KiB
PowerShell
47 lines
2.5 KiB
PowerShell
function Get-CredentialFromEnvironmentVariables {
|
|
<#
|
|
.SYNOPSIS
|
|
Get the user's credentials from the local environment variables
|
|
This is mostly useful as a Profile line such as: `$creds = (Get-CredentialFromEnvironmentVariables)
|
|
This way a developer can test faster with stored credentials without having to recreate them frequently
|
|
#>
|
|
param (
|
|
)
|
|
|
|
$logLead = (Get-LogLeadName)
|
|
|
|
$user = (Get-EnvironmentVariable -Name "CREDENTIAL_USERNAME" -Store User 6>$null 5>$null 4>$null 3>$null)
|
|
if ([string]::IsNullOrWhiteSpace($User)) {
|
|
Write-Warning "$logLead : Your cached username is out of sync with your configuration. Please update using Set-LocalUserCredential and then retry your task."
|
|
throw "$logLead : Username not present or corrupted"
|
|
}
|
|
|
|
# handy decomposition magic trick
|
|
$userPartial = ($User -split '\\')[-1]
|
|
$PasswordLastSet,$PasswordNeverExpires,$PasswordExpired = (Get-ADUser -Filter "SamAccountName -eq '$userPartial'" -Properties PasswordLastSet, PasswordNeverExpires,PasswordExpired)['PasswordLastSet','PasswordNeverExpires','PasswordExpired']
|
|
|
|
if ($PasswordExpired) {
|
|
throw "$logLead : Your password is expired, you are gonna have a real bad day mate"
|
|
}
|
|
|
|
if ([bool]$PasswordNeverExpires) {
|
|
# neat, but you probably shouldn't be using this account cached ...
|
|
} else {
|
|
$lastChangeDate = (Get-EnvironmentVariable -Name "CREDENTIAL_LASTCHANGED" -Store User 6>$null 5>$null 4>$null 3>$null)
|
|
$tempParseDate = [DateTime]::MinValue
|
|
if (![DateTime]::TryParse($lastChangeDate,[ref]$tempParseDate)) {
|
|
Write-Warning "$logLead : Your cached password record appears corrupted. Please update using Set-LocalUserCredential and then retry your task."
|
|
throw "$logLead : Stored password record appears corrupted"
|
|
}
|
|
|
|
if ($PasswordLastSet -gt $tempParseDate) {
|
|
Write-Warning "$logLead : Your cached password is out of sync with your configuration. Please update using Set-LocalUserCredential and then retry your task."
|
|
throw "$logLead : Stored password appears to be out of sync"
|
|
}
|
|
}
|
|
|
|
$secureStringPassword = (Get-EnvironmentVariable -Name "CREDENTIAL_PASSWORD" -Store User 6>$null 5>$null 4>$null 3>$null)
|
|
# If the password string is empty this just won't work so it'll throw on its own
|
|
|
|
return New-Object System.Management.Automation.PSCredential -ArgumentList $user, (ConvertTo-SecureString $secureStringPassword)
|
|
} |