-
Notifications
You must be signed in to change notification settings - Fork 4
/
GetCredential.ps1
51 lines (46 loc) · 1.36 KB
/
GetCredential.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<#
# Alternative to Get-Credential which allows one to supply credentials to
# Invoke-Command and such without the UI dialog. This can be useful for
# unattended scripts where a UI cant be used.
#
# Example:
# Invoke-Command -ComputerName srv01 `
# -Authentication Basic `
# -Credential (GetCredential.ps1 -username foo -password bar) `
# -ScriptBlock { pwd }
#
# A prompt will appear username and/or password arguments are omitted.
#>
param(
[parameter( mandatory = $false )]
[string] $Username,
[parameter( mandatory = $false )]
$Password,
[Switch] $AsNetworkCredential
)
while( [String]::IsNullOrEmpty( $Username ) )
{
$Username = Read-Host -Prompt "Username"
}
$Credential = $null
if( $Password -is [String] -and ![String]::IsNullOrEmpty( $Password ) )
{
$Credential = new-object System.Management.Automation.PSCredential( $Username, (ConvertTo-SecureString -AsPlainText -Force -String $Password) )
}
if( $Password -is [System.Security.SecureString] )
{
$Credential = new-object System.Management.Automation.PSCredential( $Username, $Password )
}
while( $Credential -eq $null )
{
$SecurePassword = Read-Host -AsSecureString -Prompt "Password"
$Credential = new-object System.Management.Automation.PSCredential( $Username, $SecurePassword )
}
if( $AsNetworkCredential )
{
$Credential.GetNetworkCredential()
}
else
{
$Credential
}