在运行Powershell脚本之前提示域管理员凭据

时间:2019-05-08 14:09:33

标签: forms powershell scripting credentials

我想在域管理员凭据下运行某些表单,我需要脚本本身中的全部内容。

我在网络上发现了一些技巧,但没有什么非常方便或期望的。我不想使用任何.bat文件或类似文件。为了给您提供信息,我使用Powershell Studio编写了所有脚本。

你们有没有一个解决方案来收集域管理员凭据,对其进行检查,最后使用这些凭据来运行脚本?

1 个答案:

答案 0 :(得分:0)

您可以使用LDAP检查域凭据:

# Load the required assembly
Add-Type -AssemblyName 'System.DirectoryServices.Protocols'

# Specify credential details
$domain = 'example.com'
$userName = 'Username'
$password = 'Password'

try {
    # Create a credential object
    $netCred = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $userName, $password

    # Create an LdapConnection object
    $connection = New-Object -TypeName  System.DirectoryServices.Protocols.LdapConnection -Argumentlist $domain
    $connection.Credential = $netCred

    # Attempt to connect
    # Will raise an exception if credentials are wrong, DC is unavailable, etc
    $connection.Bind()

    # Do something with the valid credentials
    Write-Output -InputObject "Credentials are good!"
}
catch [System.DirectoryServices.Protocols.LdapException] {
    # Failed to connect, so give the user a friendly error message
    Write-Output -InputObject "Error connecting to the '$domain' as '$userName': $($_.Exception.Message)"
}
finally {
    # Dispose of the connection
    $connection.Dispose()
}