Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function script:Invoke-Credentials {
- [CmdletBinding()]
- param(
- [Parameter(HelpMessage="Specify the username for the stored credential")]
- [ValidateNotNullOrEmpty()]
- [string]$Script_Username = "svc.username", #Username goes here
- [Parameter(HelpMessage="Specify the path to store the credential")]
- [ValidateNotNullOrEmpty()]
- [string]$Script_CredFolder = "C:\Automate\",
- [Parameter(HelpMessage="Specify the path to store the credential")]
- [switch]$Plaintext,
- [Parameter(HelpMessage="Specify the encryption key so other users can decrypt the stored credential")]
- [string]$KeyPhrase = "dGhpc2lzMTkyYml0c2FuZGF3ZXNvbWUh"
- )
- #NOTE: This credential file can be read from any account as long as the $KeyPhrase parameter used to encrypt the password is also used to decrypt the password.
- $ErrorActionPreference = "Stop"
- $Key = [Text.Encoding]::ASCII.GetBytes($KeyPhrase) #Read ASCII characters from the KeyPhrase
- $ValidKeyLengths = 16, 24, 32
- Write-Verbose "Key length $($Key.Length) bytes"
- If ($Key.Length -notin $ValidKeyLengths) {
- Write-Error "Key length must be 128, 192 or 256 bits."
- }
- Else {
- $Script_CredPath = $Script_CredFolder + $Script_Username + ".pwd"
- If ((Test-Path -Path $Script_CredFolder) -eq $False) { #Check if the $Script_CredFolder folder exists. If not, create it.
- New-Item -ItemType Directory -Path $Script_CredFolder | Out-Null
- }
- If ((Test-Path -Path $Script_CredPath) -eq $False) { #If the password file does not exist, create it -- the first run of the script must be done manually to set this!
- Write-Verbose "Credential not found, prompting for new credential"
- (Get-Credential -Username $Script_Username -Message "Enter credentials for WebUtils DB (Check SecretServer)").Password | ConvertFrom-SecureString -Key $Key | Out-File $Script_CredPath
- }
- ElseIf ((Get-ChildItem $Script_CredPath | Select Length).Length -gt 0) {
- Write-Verbose "$Script_CredPath found; using stored credentials"
- }
- Else {
- Write-Error "0kb size file found at $Script_CredPath; please delete and retry"
- }
- $Script_Password = Get-Content $Script_CredPath | ConvertTo-SecureString -Key $Key #Read the password using the encryption key
- $Script_Cred = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $Script_Username, $Script_Password #Create the PSCredential Object
- If ($Plaintext) {
- $PlainTextPassword = $Script_Cred.GetNetworkCredential().Password #Use this if a plaintext password is needed
- Return $PlainTextPassword #Delete this when implementing in a script!
- }
- }
- } #End Invoke-Credentials
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement