Created
March 3, 2016 22:56
-
-
Save zoredache/328e4848bdb7631c8503 to your computer and use it in GitHub Desktop.
Demonstration of accepting credentials from a variable or file
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
<# | |
.SYNOPSIS | |
Demonstration of accepting credentials in a variable or file | |
.DESCRIPTION | |
This is only an demonstration of how a script can accept either a file | |
with stored credentials, or a PSCredential object, so that it can be used | |
performing tasks that require authentication. | |
.PARAMETER CredentialFile | |
Allows you to use a set of credentials stored in a file that was created like this. | |
Get-Credential | Export-Clixml saved_credential.xml | |
.PARAMETER Credential | |
Accept a [System.Management.Automation.PSCredential] directly, so the script can still | |
be used by people with valid credentials that don't have a saved file | |
.EXAMPLE | |
Get your credentials and call the script | |
Get-Credential | Export-Clixml saved_credential.xml | |
.\Demonstrate-CredentialFile.ps1 -CredentialFile saved_credential.xml | |
.EXAMPLE | |
Get your credentials and call the script | |
$creds = Get-Credential | |
.\Demonstrate-CredentialFile.ps1 -Credential $creds | |
.NOTES | |
Invoke-ScriptAnalyzer Demonstrate-CredentialFile.ps1 reports a | |
warning `PSAvoidUsingPlainTextForPassword` for having a paramater named | |
`$CredentialFile` being used as a simple string. This is a **false-positive**. | |
This is not a path to a file, not a username/password/pscredential. | |
The credentials file used here will be encrypted using the Windows Crypto API. | |
A secret will be part of the profile, which means it will only be useable on | |
the machine, under the specific profile that the credential file was saved. | |
Since this file is linked to a specific profile, it probably should be saved in | |
the profile directory So something like: | |
c:\Users\username\Documents\credentialpurpose_credential.xml | |
#> | |
[cmdletBinding()] | |
param( | |
[parameter(ParameterSetName='CredVar', | |
Mandatory=$true)] | |
[pscredential] | |
[System.Management.Automation.CredentialAttribute()] | |
$Credential, | |
[parameter(ParameterSetName='CredFile', | |
Mandatory=$true)] | |
[string]$CredentialFile | |
) | |
Set-StrictMode -Version Latest | |
# Get Credentials when CredentialFile was used. | |
If ('CredFile' -eq $PsCmdlet.ParameterSetName) { | |
$Credential = Import-Clixml $CredentialFile | |
If ('System.Management.Automation.PSCredential' -ne | |
($Credential).GetType().FullName) { | |
throw "The loaded object must be a [System.Management.Automation.PSCredential]" | |
} | |
} | |
$Credential |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment