簡體   English   中英

PowerShell - 如果用戶輸入憑據,則查詢 AD 時出錯

[英]PowerShell - Error when querying AD if user enters credentials

嘗試為我的 IT 幫助台團隊創建一個基本腳本,以查詢我們的 AD 以查看計算機的主機名是否已經在域中。 我希望它不需要任何模塊,因此它可以在任何 Windows 計算機上運行而無需其他軟件(因此我使用的是DirectoryServices )。

公司編碼政策也阻止我預定義憑據,因此我想將其設為用戶定義。 但是,似乎腳本只有在預定義的情況下才能成功運行。 如果憑據是用戶定義的,則會出現以下錯誤。

使用“0”參數調用“FindAll”的異常:“用戶名或密碼不正確。”

下面是我所擁有的編輯版本。

$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"
    }

憑據可以是用戶定義的還是必須預定義的?

您正在使用的DirectoryEntry構造函數要求password參數字符串而不是安全字符串

-AsSecureString一起使用時, Read-Host輸出一個System.Security.SecureString對象。 將其轉換回string並將其作為構造函數的參數傳遞應該可以解決問題:

$secpassw = Read-Host 'Enter password' -AsSecureString
$password = [System.Net.NetworkCredential]::new('', $secpassw).Password

還值得注意的是,由於您要求輸入用戶名和密碼,因此Get-Credential可能是一種更優雅的詢問方式,並且使用NetworkCredential轉換安全字符串的相同技術將起作用:

$cred  = Get-Credential
$passw = [System.Net.NetworkCredential]::new('', $cred.Password).Password

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM