2012-05-29 4 views
9

Get-Credentialを使用して作成したPowerShellのPSCrendentialオブジェクトがあるとします。PowerShell PSCredentialの検証

どのようにしてActive Directoryに対して入力を検証できますか?今、私はこの方法を見つけたが、私はそれは少し醜い感じることで

[void][System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") 


function Validate-Credentials([System.Management.Automation.PSCredential]$credentials) 
{ 
    $pctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, "domain") 
    $nc = $credentials.GetNetworkCredential() 
    return $pctx.ValidateCredentials($nc.UserName, $nc.Password) 
} 

$credentials = Get-Credential 

Validate-Credentials $credentials 

[2年後の編集、]今後の読者のためにTest-CredentialまたはTest-PSCredentialが良いの名前であることに注意なぜならくださいValidate

答えて

8

Get-Verbを参照)は、有効なPowerShellの動詞ではありません私はSystem.DirectoryServices.AccountManagementを使用すると、以下醜いの方法であると信じて:

これは(?もっと醜い)ADSIを使用している:私はインストーラと同様の問題を有し、かつ、提供されるサービスアカウントの詳細を確認するために必要とされた

$cred = Get-Credential #Read credentials 
$username = $cred.username 
$password = $cred.GetNetworkCredential().password 

# Get current domain using logged-on user's credentials 
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName 
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password) 

if ($domain.name -eq $null) 
{ 
write-host "Authentication failed - please verify your username and password." 
exit #terminate the script. 
} 
else 
{ 
write-host "Successfully authenticated with domain $domain.name" 
} 
+0

私はPSCredentialsが認証プロバイダに依存していないことを理解しています(これは基本的にユーザー名とパスワードの単純なコンテナです)。 –

+0

@SteveB特に、(IMO)マイクロソフトがAccountManagementを行う理由は、ADで働いている人にとっては、sysadminとdevelopperにとっては本当に一般的な作業です。ここでは、この作業を行うためにC#で使用されるさまざまな方法を見ることができます:http://stackoverflow.com/questions/290548/c-sharp-validate-a-username-and-password-against-active-directory –

+0

実際には一般的な開発のベストプラクティスがここに適用されます。特に私はこの関数の複雑さを隠し、単に関数を呼び出すことができます:) –

0

。 PowerShellでADモジュールを使用することを避けたかったのは、スクリプトを実行しているマシンにインストールされる100%ではないからです。

私は以下を使用してテストを行いましたが、少し汚れていますが動作します。

try{ 
    start-process -Credential $c -FilePath ping -WindowStyle Hidden 
} catch { 
    write-error $_.Exception.Message 
    break 
} 
+1

私の質問も@cbもありません。答えは、ADモジュールがロードされている必要があります。これは、PowerShellで常に利用可能な、ADに関連するいくつかの.Netクラスに依存しています。 –