-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTest-Credential.ps1
110 lines (92 loc) · 3.42 KB
/
Test-Credential.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function Test-Credential {
[CmdletBinding(DefaultParameterSetName='Machine')]
[OutputType([boolean])]
Param (
[Parameter(ValueFromPipeLine,ValueFromPipelineByPropertyName)]
[Alias('PSCredential')]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential,
[parameter(ParameterSetName='Domain')]
[AllowEmptyString()]
[AllowNull()]
$Domain,
[parameter(ParameterSetName='Machine',ValueFromPipelineByPropertyName)]
[Alias('CN','HostName','ServerName')]
[string]
$ComputerName
)
begin{
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
switch ($PSCmdlet.ParameterSetName){
'Domain' {
try{
$server = [system.net.dns]::GetHostEntry($Domain).addresslist.ipaddresstostring | Select-Object -First 1
if(-not $server){
Write-Warning "Unable to look up a DC for $Domain"
break
}
}
catch{
Write-Warning $_.exception.message
break
}
$script = {
Param($cred,$server)
try{
$obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain',$server,$cred.username, $cred.GetNetworkCredential().password)
if($obj.ConnectedServer){
$true
}
else{
$false
}
}
catch{
Write-Warning $_.exception.message
$false
}
}
}
'Machine' {
if(-not $ComputerName){
$ComputerName = $env:computername
}
$script = {
Param($cred)
try{
$obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$ComputerName)
$obj.ValidateCredentials($cred.username, $cred.GetNetworkCredential().password)
}
catch{
if($_.Exception.InnerException -like "*blank passwords aren't allowed*"){
$true
}
else{
Write-Warning $_.exception.message
$false
}
}
}
}
}
}
process{
If($null -eq $Credential){
Write-Warning "No credential specified, default to '$env:USERDOMAIN\$env:username'"
try{
$Credential = Get-Credential "$env:USERDOMAIN\$env:username" -ErrorAction Stop
}
catch{
Write-Warning $_.exception.message
break
}
}
Try{
Write-Verbose "Checking credential $($Credential.UserName) against $($Domain)$ComputerName"
. $script $Credential $server
}
Catch{}
}
}