首页 > 解决方案 > 在 Powershell 中反复提示输入凭据

问题描述

我有下面的代码提示输入用户名和密码,如果不正确,则在 catch 语句中捕获正确的异常。但是,如何确保在输入正确的用户名和密码之前反复提示输入用户名和密码?

另一个问题是如何将输入的密码转换为安全字符串。任何帮助是极大的赞赏。

$TS_Deploy_Group = "MYADGROUP"

$get_AD_Server = (Get-WmiObject -Class Win32_NetWorkAdapterConfiguration | Where-Object { $_.DNSDomain -like "***-**.contoso.com"}).DnsDomain      

if ($get_AD_Server -ne $null)
{
    $get_Nearest_DC = (Get-ADDomainController -DomainName $get_AD_Server -Discover -NextClosestSite).Name

    $AD_Server = $get_Nearest_DC,$get_AD_Server -join "." 

    $cred = $host.ui.PromptForCredential("Authenticate to OSD:", "Enter your Operator Credentials", "", "") 

}
else
{
    [System.Windows.Forms.MessageBox]::Show("Please make sure you are connected to the Corporate Network")
} 

    
Try
{   
    $ADauth = Get-ADGroupMember -Identity $TS_Deploy_Group -Recursive -Server $AD_Server -Credential $cred
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] 
{       
    [System.Windows.Forms.MessageBox]::Show("The user" +$cred.username+ "has not been found", "User not found")
}

Catch [Microsoft.ActiveDirectory.Management.ADServerDownException] 
{       
    [System.Windows.Forms.MessageBox]::Show("Check the server name or IP configuration", "Error while contacting AD Server")    
}

Catch [System.Security.Authentication.AuthenticationException]      
{       
    [System.Windows.Forms.MessageBox]::Show("Please check the admin user name or password", "Invalid credentials")                                      
}       

if (($ADauth.name -Contains $cred.username) -ne $true) {

[System.Windows.Forms.MessageBox]::Show("The specified user is not member of the group: 

$TS_Deploy_Group", "Unauthorized user")

exit

}

Finally 
{

[System.Windows.Forms.MessageBox]::Show("Task Sequence Will Continue to the Next Step")                                     

}

标签: powershell

解决方案


我会做这样的事情:

while($true)
{

Try
{   
    $ADauth = Get-ADGroupMember -Identity $TS_Deploy_Group -Recursive -Server $AD_Server -Credential $cred
    break
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] 
{       
    [System.Windows.Forms.MessageBox]::Show("The user" +$cred.username+ "has not been found", "User not found")
    $cred = $host.ui.PromptForCredential("Authenticate to OSD:", "Enter your Operator Credentials", "", "") 
}

Catch [Microsoft.ActiveDirectory.Management.ADServerDownException] 
{       
    [System.Windows.Forms.MessageBox]::Show("Check the server name or IP configuration", "Error while contacting AD Server") 
}

Catch [System.Security.Authentication.AuthenticationException]      
{       
    [System.Windows.Forms.MessageBox]::Show("Please check the admin user name or password", "Invalid credentials")   
    $cred = $host.ui.PromptForCredential("Authenticate to OSD:", "Enter your Operator Credentials", "", "")                                    
}   
}

推荐阅读