[英]PowerShell - Error when querying AD if user enters credentials
Trying to create a basic script for my IT helpdesk team that queries our AD to see if a computer's hostname is already on the domain.尝试为我的 IT 帮助台团队创建一个基本脚本,以查询我们的 AD 以查看计算机的主机名是否已经在域中。 I want this to not require any modules so it can run on any Windows computer without additional software (because of this I am using
DirectoryServices
).我希望它不需要任何模块,因此它可以在任何 Windows 计算机上运行而无需其他软件(因此我使用的是
DirectoryServices
)。
Also company coding policy prevents me from predefining credentials, so I want to make it user-defined.公司编码政策也阻止我预定义凭据,因此我想将其设为用户定义。 However, it seems that the script will run successfully only if they are predefined.
但是,似乎脚本只有在预定义的情况下才能成功运行。 Getting the below error if credentials are user-defined.
如果凭据是用户定义的,则会出现以下错误。
Exception calling "FindAll" with "0" argument(s): "The user name or password is incorrect."
使用“0”参数调用“FindAll”的异常:“用户名或密码不正确。”
Below is a redacted version of what I have.下面是我所拥有的编辑版本。
$username = read-host 'Enter username'
$password = read-host 'Enter password' -AsSecureString
$hostname = hostname
Write-Host "Checking if $hostname is on the domain..."
$filter = "(&(ObjectCategory=computer)(Name=$hostname))"
$de = New-Object DirectoryServices.DirectoryEntry("LDAP://contoso.com/DC=contoso,DC=onmicrosoft,DC=com",$username,$password)
$ds = New-Object DirectoryServices.DirectorySearcher $de
$ds.filter = $filter
$ds.findall() |
ForEach-Object -Begin {} -Process{$_.properties.item(“Name”)} -End { [string]$ds.FindAll().Count } | Out-Null
if ($ds.FindAll().Count)
{
Write-Host "true"
}
else
{
Write-Host "false"
}
Is it possible for the credentials to be user-defined or does it have to be predefined?凭据可以是用户定义的还是必须预定义的?
The DirectoryEntry
constructor you're using requires the password
argument to be a string instead of a secure string .您正在使用的
DirectoryEntry
构造函数要求password
参数是字符串而不是安全字符串。
Read-Host
when used with the -AsSecureString
outputs a System.Security.SecureString
object.与
-AsSecureString
一起使用时, Read-Host
会输出一个System.Security.SecureString
对象。 Converting it back to string
and passing it as argument for the constructor should solve the problem:将其转换回
string
并将其作为构造函数的参数传递应该可以解决问题:
$secpassw = Read-Host 'Enter password' -AsSecureString
$password = [System.Net.NetworkCredential]::new('', $secpassw).Password
It's also worth noting that since you're asking for Username and Password, Get-Credential
might be a more elegant way for asking it and the same technique using NetworkCredential
to transform the secure string will work:还值得注意的是,由于您要求输入用户名和密码,因此
Get-Credential
可能是一种更优雅的询问方式,并且使用NetworkCredential
转换安全字符串的相同技术将起作用:
$cred = Get-Credential
$passw = [System.Net.NetworkCredential]::new('', $cred.Password).Password
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.